Should I make data private?

I know that the data in the class must be private, and then use getter and setter to read / modify. But isn't that very difficult compared to directly using student.scores.push_back(100) , which saves a member function.

 class Student { public: void addToScores(int inScore) { scores.push_back(inScore); } private: vector<int> scores; } 

In short, I'm curious what people actually do in practice, always strict private data with a getter and setter?

+4
source share
4 answers

The purpose of member functions is to open an interface. There is no need to make getters and setters or other trivial functions, just move the interfaces already implemented by members into an aggregated container object.

If the Student client should be allowed to manipulate scores , but they want to, you must make scores public member and access it in a simple way. If it should be a stack with push , pop and top , use the std::stack interface adapter. If only push_back allowed, you can implement addToScores . But if you are the only client, and you donโ€™t care that other parts of the std::vector interface are being abused, there really is no point in introducing a new interface.

Each interface within the program should be thought out. Adding slapdash interfaces as a habit, since standard interfaces (including the default C ++ assignment operator) are "dangerous", not necessarily a good habit.

+4
source

In practice, people use classes to define new data types with new semantics that are independent of their data members. Neither accessors nor public data elements are used, but member functions are provided that perform tasks related to the new data type, while preserving the invariants in the data elements.

Of course, sometimes people write classes that are just a collection of data, without additional semantics. In this case, a struct filled with public members is appropriate.

+2
source

One of the main reasons for using Get / Set methods is to control the type of input, in addition to encapsulating data.

If you do not want to take any specific input types, say, you can not evaluate the score outside the interval [0,100], then you can check this condition in the Set method so that the library user cannot make an illogical operation.

+2
source

If this is a simple read / write, you really don't need to keep the data private. But if there are validations / conditions that you need to do to read / write data, it would be wise for it to be private.

0
source

All Articles