Yalda
Yalda

Reputation: 684

When to define private fields in a class

Imagine there are several methods in a class, all of which use the same field, for example studentNumber. Is it better to fetch the value of this field (from whatever method that is available, and is not super slow) every time it is needed, or define it as private and initialize it once?

The latter has obviously better considering performance. But my supervisor always insists that we should try to write methods in a way that they function independent of the world outside that method.

Any help?

Upvotes: 0

Views: 83

Answers (2)

Joni
Joni

Reputation: 111259

Adding mutable "state" to a class using member variables can make it harder to test, and harder to use with multithreading. In general it should be avoided, if possible.

If the externally stored value is never expected to change during the life time of an object, fetching its value once and storing it does not imply mutable state, so you're safe from the above problems.

On the other hand, the current design implies a tight coupling between your code and whoever provides the value you use. This is a code smell. Perhaps a better design would be moving the responsibility of fetching the value outside of your class, and you would add a constructor parameter to accept it, in the spirit of dependency injection.

Upvotes: 1

astef
astef

Reputation: 9498

There is a problem with a second approach. Your methods become dependant on each other, because each of it can change shared resource (a field). That's called common coupling (from wiki):

Common coupling (also known as Global coupling) is when two modules share
the same global data (e.g., a global variable).
Changing the shared resource implies changing all the modules using it.

That's why I'd prefer first approach.

But if you can mark your field as readonly and set a value to it in a class constructor, I think your supervisor will agree that's OK.

Upvotes: 1

Related Questions