Private helper methods vs. public static utility methods in Java

Sabir Khan :

I have a Java class that is becoming long. When I run it through code quality tools, I get flagged for number of lines in the class.

This is a lower layer class, used by upper layers with Spring's @Autowired. The class has a lot of private instance methods which are not static. They don't use any instance fields, working only on method parameters.

Can I safely move these methods as public static in some separate utility class? What are the downsides?

GhostCat salutes Monica C. :

"Wrong" mindset here.

You do not rework your classes because tools are complaining about this or that.

You want to improve the quality of your source code; and such tools can help with identifying "topics worth thinking think about". You take their feedback as hint; not as "order".

Therefore you don't worry about "lines of codes" within a class. Instead, you worry about the responsibilities that this class has. Meaning: the line number count isn't a problem per se - but violations of the Single Responsibility Principle are.

Thus: you step back and check out what exactly your class is doing. And when it is clearly doing more than one thing, you extract such aspects into other classes!

Meaning: if you actually find that all this code "belongs" to the responsibility of that class; then keep it in there. Don't start putting internal implementation details into unrelated helper classes; just because some tool warns you about number of lines.

On the other hand, turning private methods into something that is static/package protected would allow you to unit test those methods. Which could be an advantage. But as said: as long as we are talking about implementation details, they should stay private; and they shouldn't be unit tested anyway.

Long story code: know and understand what "clean code" is about; and try to follow the ideas outlined there.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=422173&siteId=1