Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of having a private attribute with getters and setters? [duplicate]

Tags:

java

c++

oop

In object oriented programming, I used to have this question and I still do :

What would be the benefit of declaring a class member as private if we will create for it a public getter and a public setter?

I don't see any difference at the security level between the case above and the case of declaring the class member as public.

Thanks!

like image 420
loulou Avatar asked Sep 17 '13 09:09

loulou


2 Answers

Encapsulation provides data hiding and more control on the member variables. If an attribute is public then anyone can access it and can assign any value to it. But if your member variable is private and you have provided a setter for it. Then you always have an option to put some constraints check in the setter method to avoid setting an illogical value.

For example a class with public member only :

class MyClass {
    public int age;
}

public MyClassUser {

    public static void main(String args[]) {
        MyClass obj = new MyClass();
        obj.age = -5 // not a logical value for age
    }
}

Same class with private member and a setter:

 class MyClass {
     private int age;
     public void setAge(int age) {
         if(age < 0) {
            // do not use input value and use default
         } else { 
            this.age = age;
         }
     }
 }
like image 128
Juned Ahsan Avatar answered Oct 12 '22 14:10

Juned Ahsan


If your class has no invariants to maintain then writing public getters and setters for a private data member is pointless; you should just use a public data member.

On the other hand, if you do have invariants to maintain then using a setter can allow you to restrict the values that can be assigned to the data member.

Note that just because you have a data member doesn't mean you have to write any getters or setters for it.

Pet peeve: "but what if the internals change?" It doesn't matter. You had a getName function that returned a std::string const&. Getters reduce encapsulation because they constrain your choices when changing the implementation later on.

like image 34
Simple Avatar answered Oct 12 '22 13:10

Simple