Unit Testing – Why No Parameters Are Better Than Few Parameter Methods

clean codemethodsparametersunit testing

In Clean Code, Robert C. Martin states that no parameter methods are better than those with very few parameters. I'm kind of confused as no parameter methods are usually harder to unit test and tend to be more coupled.

I think his rational is that since a class should only fulfill one very specific task the coupling is alright but what about unit testing?

Also the approach towards atomic methods would favor reuse of the methods so why would you try to couple them to instance methods preferably?

Best Answer

My understanding of Uncle Bobs claim is: think carefully about the life cycle of your objects.

I for my self found that quite often I can turn some of the method parameters into constructor parameters since they do not change during the use of the object.

In contrast to Uncle Bobs I don't find no parameter methods superior. That is because my methods often create a return value that is used in the next method. Adding that return value to the objects state instead of passing it as parameter to the next method decreases readability because it hides a dependency between those methods. This also becomes a problem when you apply your IDEs automated refactoring move method which makes the (temporary) member variable accessible for the object the method moved to...

Also it opens the possibility to change the order of method in a wrong way. The "no state" version would throw a compiler error in such case...

Related Topic