If I can change the value of private variable through getter-returned reference then isn't it bypassing the setter method? Doesn't it defeat the purpose of getter-setter and private variables
public class Test{
private Dimension cannotBeChanged;
public Test(int height, int width)
{
if(height!=3)
cannotBeChanged.height = height;
if(width!=3)
cannotBeChanged.width = width;
}
public Dimension getDimension()
{
return cannotBeChanged;
}
public void setDimension(int height, int width)
{
if(height!=3)
cannotBeChanged.height = height;
if(width!=3)
cannotBeChanged.width = width;
}
public static void main(String [] args)
{
Test testOne = new Test(5,5);
Dimension testSecond = testOne.getDimension();
testSecond.height = 3; //Changed height and width to unwanted values
testSecond.width= 3;
}
setting them as private won't add any value because they will be not accessible from outside the class and accessible from inside without having the setters and getters at all. Therefore, the answer is: They must be public members.
We require a setter method to update the value of a private variable from outside of the class and a getter method to read the value of that variable. It allows developers to control how the main variables in the code are accessed and updated.
In classes, variables are often made private for encapsulation, and to limit the variables to a certain scope allow better error control and fewer bugs. This makes sense, as the fewer places a variable can be accessed the fewer places a bug can occur with that variable.
The private getter/setter methods provide a place for adding extra behavior or error checking code. They can provide a place for logging state changes or access to the fields. They can provide a place for adding your debug code while testing.
Yes, It does. I have the following conclusion in getters and setters from the Clean Code book; you can use it if you really accept it.
Programmer should devise the ways for external entities to touch the secured variables of his program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With