Pass in through a constructor, and then call – or pass in directly through a method? – A Question of Design (OOP)

_config.yml

Another interesting thought: is it best to pass parameters into a method, or is it best to store the value in an instance variable?

Consider this situation:

What benefit is there in storing the x and y variables within the class? We actually don’t need it here. Moreover it obfuscates the code somewhat. In my opinion, where possible, you want to eliminate the use of temporary variables and you also want to see, very transparently, the inputs required to produce a given output. In this case, a class like this would be much more transparent, without having any loss in functionality:

  • Now you can clearly see what goes into the method and what comes out. And secondly:
  • If you want to extract that method into a separate class – you can more easily do so.

Summary

As a general rule, I think it is much better to eliminate those temporary variables where possible, and to substitute a method – perhaps repeatedly if necessary – just to make the code more readable, and easier to change. If you have a good reason to do otherwise – performance for example, then you can refactor later. This is the line touted by Martin Fowler and conventional wisdom suggests to unquestioningly follow what ever Fowler says without any critical thinking whatsoever. We shall all duly oblige.

Written on October 15, 2017