What good are public variables then?

后端 未结 14 2287
悲哀的现实
悲哀的现实 2020-12-09 15:16

I\'m a total newbie with tons of ?\'s in my mind and a lot to experience with C++ yet! There\'s been something which I find really confusing and it\'s the use of public vari

14条回答
  •  情深已故
    2020-12-09 15:40

    Anything exposed as public becomes part of the contract of that object. If you expose data publicly then it must continue to behave properly when the data values are changed. For struct type objects this may well be appropriate.

    Having a high number of getters and setters can be a warning sign that the object is really a struct and it may be better to expose the fields directly. However, I have implemented struct type objects in order to allow fields to have multiple names. Fields could have multiple setters or getters as required allowing name translation between different domains. The real fields had descriptive names. Additional getters and setters used the domain specific codes for those fields.

    As other have noted, getters and setters are indicative of the presence of a field. There is no requirement that such a field exist, only that its behavior exists. Making the getters and setters public implies there is a reason for the public to be able to modify or read the value of that field. Think twice about the purpose, and you may change the method name or not make it public.

提交回复
热议问题