The pseudo-code is in JavaScript. I have the class Animal
and the method typeMatches
that uses private variable _type
that holds the type of the animal:
function Animal()
{
this._type = "dog";
}
Animal.prototype.getAnimalType = function()
{
return this._type;
}
Animal.protytype.typeMatches = function(animalType)
{
//option 1 - accessing private variable directly
return this._type === animalType;
//option 2 - accessing private through public method
return this.getAnimalType() === animalType; //accessing private through public method
}
I've always used private variables directly from inside the class (option 1), however I was told recently that it's a bad practice and I should use public methods to get private variables whenever I have a chance to do so (option 2). But I question this advice on the grounds that the variable is private and I'm using it inside the class so I'm not breaking any conventions, while the direct access makes my code clearer to me. Am I wrong?
Do it when it's absolutely needed (and avoid it whenever possible).
The only task of a getter is to return the data, perhaps after a transformation to make it more easy to use.
For example the backing field
long _ticks = 500000000000L;
Can have a getter
public long GetTicks()
{
return _ticks;
}
It is indeed correct that in this case there is no difference between using the backing field and the getter. The problem with using getters however is that you are now making both your external and your internal representation of the data the same.
We can express very easily why this is a problem: what if we want to return our _ticks
as a string
to the outside world? Now we have to break internal functionality or otherwise we won't be able to change something as ordinary as a public interface.
Indeed: the very thing we are trying to accomplish with the encapsulation of our private fields is now broken because you would be trying to use external representation inside the internal functionality.
This code will now break other code inside our class that relied on it being passed a numeric type instead of a string
.
public string GetTicks()
{
return _ticks.ToString();
}
There are very, very little situations where I would advocate the use of a getter inside the class itself (a calculated field like @Noel's GetAge()
comes to mind) and if I do it's because it's the last feasible option. Keep your internal and external representation separated, it will save you headaches.
(I'm not very familiar with Javascript but I believe the code samples are clear enough. I realize Javascript cares less about exact types but this is merely an example: there are many different kinds of transformations possible.)