Search code examples
javaoop

What is the purpose of having private variable with corresponding setter method?


When we have a setter method for private variable in java, what is the purpose of making the variable private?

We are having private variables to restrict the user not to access the state of an instance directly. But in sometimes, we are having corresponding setter and getter methods to access and change the state of the private variable. If so, then why do we make the variable private? We can just have public variable instead right?


Solution

  • The rationale is that you're hiding the implementation. When you call

    setX(23);
    

    your corresponding variable x is hidden from client classes and can't be directly observed or modified.

    Why is this good ?

    1. it hides the implementation. You can change x at a later date to (say) a string, a double etc. and your client code doesn't have to change. x could even disappear and calling setX() would actually perform some different but equivalent function.
    2. by implementing a setter function, you can enforce validation etc. Otherwise you can't prevent someone setting x to an invalid (e.g. negative) value.
    3. (this is a Java-specific benefit rather than a general OO benefit). Lots of Java frameworks work with objects using the JavaBeans convention. i.e. for a property x there will exist a corresponding getX()/setX() (or isX() if it's a boolean). By adhering to convention your class will interoperate nicely with these frameworks.

    Note there are arguments for not having setters but rather implementing immutable objects (so you'd set your value via the constructor alone). That makes the object thread-safe and debugging/reasoning about the object state easier.