2

I've just learned about OOP. I'm kind of confused about private members in a class.

I saw examples about setting variable members to private so it's not be changed anywhere else.

But on the other hand, there are public methods like getName() and setName() to get and set the private member Name for instance.

What is different between changing it through methods and changing it directly? Can anyone explain it for me, please?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
xwhitelight
  • 1,569
  • 1
  • 10
  • 19
  • 1
    You want to read about Access Modifiers my friend. Here is a link. https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html – John Paul Feb 24 '16 at 10:42

4 Answers4

4

The main argument for this pattern is encapsulation as described in this answer.

But admittedly in your name example there is not much encapsulation.

Here are two advantages of getter/setter methods vs public fields:

  1. When setting a value through a setter method you can check and reject invalid values whereas if a field is public you can't control what values are assigned to it.

  2. You don't need to provide a setter and getter method, giving you the possibility to make a field effectively read-only or write-only.

Community
  • 1
  • 1
wero
  • 32,544
  • 3
  • 59
  • 84
1

Changing it with methods give you more control on the logic you want to apply to access your member variables.

For example if a member variable is a readonly variable, you can omit the implementation of set method so nobody can write to the content.

Or on the other hand if you want to just write to a variable and don't want anybody read it later you can just implement set methods.

One other thing that setters will provide you is that you can have a validation before committing the value. For example if you expect a string of a certain format to be set to a member string variable, you can check it in the setter function and accept it if it matches the pattern or reject it if it doesn't.

It is generally the best practice to change/read the member variables through getters and setters

Pooya
  • 6,083
  • 3
  • 23
  • 43
0

As a general rule of thumb, you want to be as restrictive as possible on your class properties and extension points (private > protected > public). This is particularly important in projects that run for a long period of time and need maintenance and re-factoring.

It's quite difficult to restrict your properties from public to protected/private once they have been used for a while, because you don't know how many other classes are relying on those properties being public. On the other hand, relaxing from private to protected/public is less traumatic because you don't have to worry about previous access to that property from without that class.

Having said that, getters and setters provide you with unique points of contact to interact with private members of a class. That's called encapsulation in OOP. That means that you can ensure that everyone that interacts with those properties are doing it in the same and consistent manner. A silly example would be normalization of the property:

private String name;

public void setName(String name) {
    this.name = StringUtils.capitalize(name);
}

You're ensuring here that whoever sets a name does not need to care about its capitalization, because you're enforcing it through the setter. Same could apply to a getter, applying business rules as needed.

Compare that with accessing a public property which you then need to capitalize on your end every time you use it...

Finally, I'd say that blindly adding getters and setters to your objects is a bad practice. Only provide those accessors when there's a good reason for them to exist. For instance:

class Person {

    private name;

    public Person(String name) {
        this.name = name
    }

    public String name() {
        return name;
    }
}

You normally don't set the name to a person, so we can omit that setter all together. But every person has a name. That being the case, you can enforce it via its constructor. This makes that distinction explicit, enhancing your design and preventing your object from being in a non-consistent state.

hasumedic
  • 2,139
  • 12
  • 17
0

Read this forum post . You may find lot of valuable points to get understand the concepts. http://www.cplusplus.com/forum/lounge/101305/

Following example class of getters and setters shows few good practices. We need to use const type qualifier etc. Also we can validate the values inside the implementation.

Eg:-

class ClassName{
     string name;
     int age;
     int weight;
public:
     void setName(string strName);
     void setAge(int iAge);
     void setWeight(int iWeight);
     string getName() const { return name; }
     int getAge() const { return age; }
     int getWeight() const { return weight; }
};

I can summarize following good reasons of using accessors :

  • Making future changes easier
  • Encapsulation of behaviors with property
  • Insulating your public interface from change
  • Set different access levels
  • Validate values prior to setting or getting
Shamendra
  • 176
  • 3
  • 14