I'm a first year computer science student. We are currently programming in java and I often try decompose my program into well named methods so that my main method logic can read as close to pseudo-code as possible.
The problem I find is that often I'm ending up writing so many small private methods that I feel I might be overdoing it. Are there any good rules of thumb or stylistic considerations to take into account when deciding whether to decompose a problem even further?
The rule of thumb is the Single Responsibility Principle. Every unit of code should be responsible for exactly one thing. That applies to methods as well as classes. If you can put a simple, concise name to what each of your many private methods are for, then it's fine. If you can only describe it as "part of" a larger operation, then it probably shouldn't be a separate method.
But from your question, it sounds like you're doing it right already.
Most new developers go the other way - huge functions that have many responsibilities. Your situation is infinitely preferable to this!
There's very little downside to creating lots of small methods, and lots of upside!
Short methods are:
Considering this, I would suggest that you mercilessly refactor duplication into small methods. Your IDE will give you an extract method refactoring to make this faster.
I also think your aim of aspring to a sort of readable pseudo code is, in general, a good one. A lot of the code you see won't be written like this, but it can really aid readability and the notion that 'code is documentation.'
Some people will talk about performance overhead of method calls, but only in very rare cases would that be a concern to you.
Edit - Other posters have mentioned Single Responsibility Principle. Though this is a good guideline, I personally think it goes further than this. Even some code fragment that has one well defined responsibility could potentially be decomposed for reuse and readability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With