Should I really use getters and setters for all public variables in the classes?

Asked

Viewed 47 times

1

So this subject seems very controversial but at the same time I don’t see a call among developers.

  1. Some say that getters and setters are 100% rule to access any variable within a class. That is, if I have 10 variables, I will have 10 getters and 10 setters;
  2. It has to be said that getters and setters should be used only for specific situations;
  3. Finally there are those who argue that one should not use absolutely getters and setters for public variables, since they are public and easily accessible.

So, in a simple structure like this:

class exemplo
{
public:
    int a, b, c, d, e, f;
    string g, h, i, j;
    double k, l, m, n, o, p, q, r, s, t;
};

... where there are 20 public variables, I really have to have 20 getters and 20 setters?

  • What would be the benefit in writing getters and setters for those 20 data members?

  • The attributes are public, whether or not implementing the getters/setters, you will never ensure that all customers in the class will use them.

  • The use of getters and setters is recommended in all scenarios regardless of the number of member variables. As a general rule, the only cases where getters and setters are dispensable are when variables are classified as private, or when it comes to a class-value.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.