Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

oop

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?

like image 676
Rajkumar Avatar asked Sep 26 '12 12:09

Rajkumar


2 Answers

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.

like image 195
Brian Agnew Avatar answered Oct 31 '22 22:10

Brian Agnew


It isn't a question of having a setter or not, it's a matter of encapsulation: member variables should almost always be private in order to hide the implementation.

Here's a good example I've recently seen: someone was asking why Java doesn't have an AtomicFloat type and someone else pointed out that you can actually implement it using AtomicInteger and doing bit tricks to convert back and forth between int and float. Now the class looked something like:

class AtomicFloat {
     private AtomicInteger value;

     public float get() {
         // turn value into float
     }

     public void set(float newValue) {
         // turn newValue into int
     }

     // CAS and whatever else
}

Now to the outside it seems I have all I need: I can use this class as an AtomicFloat and I don't care about what's going on inside. Now imagine if the user could peek in and see that all my methods are actually doing stage magic with an AtomicInteger. That would really mess things up!

like image 28
Tudor Avatar answered Nov 01 '22 00:11

Tudor