Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Imagine you have 2 methods :

  • GetConsolidation([...]);
  • GetReportOfConsolidation([...]);

These 2 methods use the same "behavior" (some local variables assigned with data) like :

var data = GetDataOfClient(foo, bar, );
var consolidation = GetConsolidation();
//etc etc...

Actually, code is just copy/pasted from one method to another etc. How can I refactor that, and if so there a name for that pattern / refactoring?

share|improve this question

closed as not a real question by Joris Timmermans, Bart van Ingen Schenau, gnat, Yusubov, MichaelT May 16 '13 at 12:44

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

3  
You need to post more code for more understanding –  Cuong Le May 16 '13 at 8:23
2  
It looks like what you need it method extraction. Though its hard to say without having the details. –  superM May 16 '13 at 8:26
add comment

1 Answer 1

Your current description could use clarification - calling functions and assigning them to local variables generally doesn't do anything useful except for the side effects of the calls.

Also if the two methods were exactly the same code as your question suggests then you'd really only need one method, and call that from the places where you now call the two differently named but the same methods..

My best guess is that your actual situation could benefit from applying the extract method refactoring.

You would turn this:

MethodA() {
  var a = CallA();
  var b = CallB(); 
  // ..  Code specific to MethodA ...
}

MethodB() {
  var a = CallA();
  var b = CallB(); 
  // ..  Code specific to MethodB ...
}

into this:

ExtractedMethod() {
  var a = CallA();
  var b = CallB(); 
}

MethodA() {
  ExtractedMethod();
  // ..  Code specific to MethodA ...
}

MethodB() {
  ExtractedMethod();
  // ..  Code specific to MethodB ...
}
share|improve this answer
    
Yep but what is the most elegant way to get access to a and b variables if you extract them from a method ? References ? An object returned by the extracted method who contains a and b ? –  eka808 May 16 '13 at 9:15
    
@eka808 - the answer is "it depends" - in this case on what is actually different between methods A and B, and how they use the variables they share. Please edit your question to include more information about this if you want more direct answers. –  Joris Timmermans May 16 '13 at 9:37
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.