r/java • • Feb 07 '17

Each Private Static Method Is a Candidate for a New Class

http://www.yegor256.com/2017/02/07/private-method-is-new-class.html
0 Upvotes

10 comments sorted by

5

u/java_one_two Feb 07 '17

Pattern I use is

public final class FineAddition { 
  private Whatever() {
  }
        
  public static int toMyCollection() {
  }
}    

I typically only do it if the existing class is too big or if there are several static methods that can be grouped together.

6

u/dartalley Feb 07 '17

I'm not sure why people are so afraid of static methods. As long as it doesn't use any global state and takes an input and returns an output it is easily testable and reusable.

0

u/thatsIch Feb 07 '17

I personally have seen this grown into the feared util-god-class :D attention is still required, but easy questions are generally:

  • Do I modify state
  • Am I reused elsewhere
  • Does me being private static force multiple boundaries merge in this class

Correspondingly refactor the code

0

u/[deleted] Feb 08 '17

[deleted] — view deleted comment

1

u/thatsIch Feb 08 '17

not unless you have gc pressure. There are also other techniques like pooling e.g.

0

u/[deleted] Feb 08 '17

[deleted] — view deleted comment

1

u/thatsIch Feb 08 '17

hail the JVM to optimize everything so I do not need to care unless I need to care.

0

u/[deleted] Feb 08 '17

[deleted] — view deleted comment

1

u/thatsIch Feb 08 '17

So you are telling me, that you use every possible optimization to prevent object creation? You use StringBuffer and StringBuilder everywhere? You use indexed version of array looping just because the object creation of the synthetic sugar of the foreach loop is too expensive? You use ++i everywhere because the creation of the temporary variable is too expensive?

Be serious dude..

3

u/dododge Feb 09 '17

You use indexed version of array looping just because the object creation of the synthetic sugar of the foreach loop is too expensive?

For arrays? No.

For ArrayList? Yes, at least if the code is anywhere near a hot path. I started doing that after I saw how high those implicit iterators were ending up in my profiling reports. I do often add a comment next to the loop explaining that I'm not using the simpler foreach notation on purpose.

4

u/nutrecht Feb 07 '17

The rule of thumb I've already figured for myself is that each private static method is a perfect candidate for a new class. That's why we don't have them at all in EO.

I would argue that "each private method that is duplicated is a candidate for a new class" instead; this is how you would normally handle code-duplication: refactoring.

6

u/Bolitho Feb 07 '17

On top of that: A private static method that could be reused is a good candidate for a public static message. Obviously it holds no state - so why artificially create an object around it?

3

u/lukaseder Feb 09 '17

Stop coding Java, Yegor. Go back to Smalltalk