Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decomposition in java, when is enough enough?

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?

like image 556
kontrarian Avatar asked Aug 16 '10 12:08

kontrarian


2 Answers

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.

like image 195
jalf Avatar answered Oct 13 '22 19:10

jalf


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:

  • Easier to reuse
  • Easier to test
  • Easier to read and understand
  • Easier to debug

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.

like image 37
Benjamin Wootton Avatar answered Oct 13 '22 21:10

Benjamin Wootton