What is the advantage of having a private attribut

2019-04-06 05:24发布

This question already has an answer here:

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!

标签: java c++ oop
15条回答
▲ chillily
2楼-- · 2019-04-06 06:13

Declaring variables as private is called as Encapsulation in Java.
Here are few advantages of using Encapsulation while writing code in Java or any Object oriented programming language:

  1. Encapsulated Code is more flexible and easy to change with new requirements.
  2. Encapsulation in Java makes unit testing easy.
  3. Encapsulation in Java allows you to control who can access what.
  4. Encapsulation also helps to write immutable class in Java which are a good choice in multi-threading environment.
  5. Encapsulation reduce coupling of modules and increase cohesion inside a module because all piece of one thing are encapsulated in one place.
  6. Encapsulation allows you to change one part of code without affecting other part of code.

one more advantage is

Making variables private in java and providing getter and setter for them makes your class compatible Java bean naming convention

查看更多
Fickle 薄情
3楼-- · 2019-04-06 06:14

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.

查看更多
欢心
4楼-- · 2019-04-06 06:15

Your question is indeed the difference between Fields and Properties. Fileds are usually private and properties do expose them. Bellow is a quote of a brilliant answer on SO:

Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.

What is the difference between a Field and a Property in C#?

In C# automatic properties will create a filed for you without having to manually declare it:

public Prop { get; set; }
public Prop { public get; private set; }
public Prop { private get; public set; }
// etc, you can specify access modifier as per your need
查看更多
一纸荒年 Trace。
5楼-- · 2019-04-06 06:16

One of the most important concepts of Object Oriented Programming is encapsulation. You encapsulate data and the methods that act on that data together. Ideally, data should be accessed only via its related methods. And the state of data should be "queried" by other objects via these methods. Making a variable public will result in that variable being directly available to all other objects breaking encapsulation.

查看更多
The star\"
6楼-- · 2019-04-06 06:18

As with any encapsulation: it hides implementation details. This allows you to control access and provide a stable interface even when the internals change.

Setter controlling access

class Person  //version 1.0
{
  std::string name;

public:
  std::string getName() const { return name; }

  void setName(const std::string &newName)
  {
    if (!newName.empty())  //disallow empty names
      name = newName;
  }
};

Getter useful during API evolution

class Person  //version 1.1
{
  std::string firstName;
  std::string lastName;

public:
  std::string getFirstName() const { return firstName; }

  void setFirstName(const std::string &newFirstName)
  {
    firstName = newFirstName;
  }

  std::string getLastName() const { return lastName; }

  void setLastName(const std::string &newLastName)
  {
    if (!newLastName.empty())  //disallow empty last names
      firstName = newFirstName;
  }

  std::string getName() const
  {
    std::ostringstream s;
    if (!firstName.empty())
      s << fistName << ' ';
    s << lastName;
    return s.str();
  }

  void setName(const std::string &newName)
  {
    setFirstName(splitUntilLastSpace(newName));
    setLastName(splitFromLastSpace(newName));
  }
};
查看更多
干净又极端
7楼-- · 2019-04-06 06:19

If you have a data transfer object, with limited scope and by design it should have no logic associated with it, I don't see a value in getters and setters.

However, if you have a component which may or may not have some logic associated with it or it could be widely used, then it makes sense to hide the details of how the data is stored. Initially it might appear that all the getters and setters are trivial and just fill up you class, but over time you might add validation to the setters and even change the getters. e.g. you might drop a field (and return a constant in future), store the data in a delegated object or compute the value from other fields.

查看更多
登录 后发表回答