Over the past couple of months of Java programming I’ve been cramped upon the use of getters and setters.
I have found that they do have a time and place however I’ve mostly found them to be extremely useless to variables you wish to externally modify.
public int a=5;
int b = a;
a = b*2;
////////////////////////////////////using get/set
private int a=5;
public int getA()
{
return a;
}
public void setA(int value)
{
a = value;
}
int b = A.getA();
A.setA(b*2);
In these cases, get/set methods are useless, yet people like my programming teacher says we must use get/set all the time.
I realise that the get method has it’s uses for safety reasons so you don’t accidentally overwrite the variable if you only want your variable to be read externally.
However, if you want to read/write to an external public variable, the use of getters and setters is useless, so why do people still do it?
Is it purely because that’s the OOP approach of accessing public variables?