Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Let's say the method foo() has lot of code and it also includes doing something for bar1, bar2 and bar3, maybe setting some status or print something or something else which is being done in just one line (note that bar1(), bar2() and bar3() are not getter/setter of that class).

The question is what would the preferred way to do this in java - are those methods ok to have just one line or remove those tiny methods and include those code in method foo() ?

class Test {
  public void foo() {
    bar1();
    bar2();
    bar3();
    // rest of the code goes here...
  }

  private void bar1() {
    // do something for bar1
  }

  private void bar2() {
    // do something for bar2
  }

  private void bar3() {
    // do something for bar3
  }
}
share|improve this question

closed as off-topic by 200_success, Nikita Brizhak, rolfl, Mat's Mug, Malachi Jan 17 at 14:30

If this question can be reworded to fit the rules in the help center, please edit the question.

    
This question appears to be off-topic because it does not contain "real" code. –  Nikita Brizhak Jan 17 at 8:46
2  
This question appears to be off-topic because it is about hypothetical code, and the best way to use function calls depends on real use cases. –  rolfl Jan 17 at 11:30

2 Answers 2

I think it's perfectly OK to create functions that might be only a couple of lines long, because it will usually make your code read more like what it is doing. Especially if you create method names that clearly articulate the objective of that function.

By doing this:

  • I have found that I gain a better understanding of the problem that I am solving.
  • I tend to find potential opportunities for reuse of those functions. Many times, they end up supporting things that aren't necessarily central to the class, and when their "purpose" becomes more clear, they can be easily factored into a new class.
  • The dependencies of the class and how they are being used are usually more clearly shown.
share|improve this answer
    
+1 - ditto. Its not about Java, it's about solving the problem. –  radarbob Dec 12 '12 at 23:08

I factor out common patterns, no matter how short they are. As example, Haskel's map function

     map f (x:xs)  =  f x : map f xs

It is a great one liner, combining 5 statements.

I also factor out the common concepts even though they are simple redirects. It is particularly useful for logging. Instead of calling System.out.println, I define a method log(String msg){System.out.prinln(msg)}. This allows me to redirect the output stream.

Otherwise, I see no reason to clog your object namespace with useless stupid routines.

share|improve this answer

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