Issue
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?
Solution
"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.
Answered By - GhostCat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.