Java – Prefer class members or passing arguments between internal methods

class-designcode-qualityjavamethodsvariables

Suppose within the private portion of a class there is a value which is utilized by multiple private methods. Do people prefer having this defined as a member variable for the class or passing it as an argument to each of the methods – and why?

On one hand I could see an argument to be made that reducing state (ie member variables) in a class is generally a good thing, although if the same value is being repeatedly used throughout a class' methods it seems like that would be an ideal candidate for representation as state for the class to make the code visibly cleaner if nothing else.

Edit:

To clarify some of the comments/questions that were raised, I'm not talking about constants and this isn't relating to any particular case rather just a hypothetical that I was talking to some other people about.

Ignoring the OOP angle for a moment, the particular use case that I had in mind was the following (assume pass by reference just to make the pseudocode cleaner)

int x
doSomething(x)
doAnotherThing(x)
doYetAnotherThing(x)
doSomethingElse(x)

So what I mean is that there's some variable that is common between multiple functions – in the case I had in mind it was due to chaining of smaller functions. In an OOP system, if these were all methods of a class (say due to refactoring via extracting methods from a large method), that variable could be passed around them all or it could be a class member.

Best Answer

If the value is a property of the class, keep it in the class. Otherwise, keep it outside. You don't design your class methods first. You design its properties first. If you did not think of putting that property inside the class in the first place, there is probably a reason for that.

The worst thing you can do, in terms of scalability, is changing your code for convenience. Sooner, rather than later, you'll find your code is bloated and duplicated. However, I must admit. Sometimes, I break this rule. Convenience is just so damn appealing.

Related Topic