In c ++, I am a beginner and cannot understand why, in fact, getters and setters are needed? Why can't we just make the variables inside the class global and change them directly? What is the need to make a variable private and create functions to modify it or get its value?

  • Getters and setters allow you to perform actions other than setting / getting the value of a variable. For example, int a = obj.temperature can initiate data exchange with equipment, if done through a getter. - Vladimir Martyanov
  • one
    Here you will be told a lot of things right now, just keep in mind that in real programming (I do not take into account the development of different frameworks and the like of shells ), this technique makes almost no sense. - avp
  • one
    @avp: it does, you just need to be able to apply it to the place - Kromster
  • @KromStern, or 99% of programmers do not know how, or they each time consider it inappropriate in the next program (however, perhaps this does not apply to the wind world (I don’t write there)) - avp
  • 3
    Here is a similar question about properties in C # . - VladD

5 answers 5

There are many advantages, and here are some of them:

  • you can selectively give access only to the getter or only to the setter
  • prevent change of a variable from the side (giving a getter a copy of it)
  • I'm not sure about C, but you can set breakpoints on access methods to find out who asked where and from
  • additional code can be added to the getter and setter
    • when setting a value, check its validity (and, for example, throw an exception)
    • when setting the value, initialize some related things
    • get a getter value not from a variable, but calculate it
    • log access to the getter / setter
    • implement and override the behavior of the getter / setter in the child classes

In general, you can do without them, but then the size of the code will grow, more time will be spent on debugging, the compiler will not be able to warn against related errors. And the larger / more complex the project, the more benefits they will bring.

    The main point is to separate the implementation from the interface.

    Thus, on the one hand, changes in the implementation do not affect the class user interface, and, on the other hand, a class user who has access to it through the open interface will not be able to violate the declared correct class behavior.

    In a class there may be dependencies between its members. Therefore, a class object should be aware of when a member of a class has undergone a change by the user in order to conform to the status of other members of the class in accordance with this change.

    For example, if your temperature class contains two data members, Celsius temperature and Fahrenheit temperature, then if the user changes one of the temperatures, then the class object must recalculate the other temperature so that their values ​​are consistent with each other.

    Generally, this is called one word инкапсуляция .

    Wanting to write this word correctly - encapsulation, - I looked at how it is written in the dictionary, and the dictionary, among other things, gave the following explanation to the word:

    Encapsulation is an immune response in insects in response to parasitic invasion.

    Paraphrasing this definition in relation to classes, it can be said that encapsulation in OOP is an immune response of a class in response to incorrect actions of users regarding its objects. :)

      Typical error example

       Object obj = new Object(); if(obj.properties = null) return false; // Опечатка, которую трудно отловить if(obj.getProperties() = null) return false; // не скомпилируется, так как результату функции нельзя присвоить значение if(obj.getProperties() == null) return false; // Правильный вариант 

      getProperties () returns the value, and only the variable can participate in the assignment operation on the left side!

      • one
        Which language do you use? If, for example, C #, then the second sentence will also not compile. And I think what you mean obj.properties instead of Object.properties. :) - Vlad from Moscow
      • I was not tied to a specific language, I gave a simple example of the benefits of heterosexuals - ActivX
      • Not bad definition with insects ++ - ActivX
      • 2
        In fact, this example is controversial, since the third sentence, in fact, is no different from the second. A function may return, for example, a reference to a pointer. - Vlad from Moscow
      • one
        I think that for many people this comment will be incomprehensible: // they will not compile as the output is constant. What does he mean? - Vlad from Moscow

      In addition, already written above, I will add from myself that in a multithreaded application it is not a recommendation / axiom / good form, but simply a necessity. Also, it allows you to implement attributes that are not inherent in the usual ivar. For example: copy, weak, strong, already mentioned above readonly.

      In other cases, it is necessary to build on the task. For example, in some screaming engines, where everybody counts, perhaps an extra method call will be evil. Also, access methods for internal ivar sometimes look strange. Do not forget that the patterns exist to solve a certain range of tasks, and not just to follow them blindly for the sake of the patterns themselves.

        In theory, from the point of view of the PLO, directly accessing the fields is considered bad tone:

         class MyClass { public: int field; }; MyClass a; a.field = 1; // Это как бы неправильно 

        To work with a field, you need to write methods (for example, getters and setters):

         class MyClass { private: int field; public: int getField() { return field; } void setField(int value) { field = value; } }; MyClass a; a.setField(1); // Это как бы правильно 
        • five
          "It is considered a bad tone .. getters and setters are needed .. this gives obvious advantages" Such an answer to the question does not contain an answer. - Kromster
        • Why not answer, yet what answer! There is such a concept in mathematics as an axiom ... So in the PLO, it is not advised to directly refer to the fields - this is like an axiom, therefore they use methods (for example, getters and setters). - sitev_ru
        • five
          Who and does not advise anyone to refer to the fields? Who thinks this is a bad tone? What are the benefits (not obvious to everyone)? Who invented the PLO and where did they register all this? - Nick Volynkin
        • four
          It is necessary at least to describe what the creation of getters and setters provides for the "obvious" advantages. They are obvious to those who have long been engaged in the development of the PLO, but not yesterday's student. - Vesper
        • one
          @sitev_ru the word "obvious" means "undoubted, indisputable, understandable at first glance." Your answer is obviously equivalent to "the benefits are clear at a glance." although the fact of the question itself shows that it is not. it does not summarize and does not complement the remaining answers, so there is obviously no point in it. - PashaPash