What good are public variables then?

后端 未结 14 2123
悲哀的现实
悲哀的现实 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:42

    IMO the most compelling reason for setters/getters is isolating change. If you need to add range checking, for example, if you already have a setter, you can easily do that in your setter without impacting client code. If you don't already have a setter, then all client code needs to be updated to use getters/setters which could be a nightmare.

    0 讨论(0)
  • 2020-12-09 15:45

    It is just a basic practice. You design the public interface of a class which can be safely accessed by the callers. If they are just methods, their content can be changed later. If they are public data members you are stck with them forever. You can not change what a public variable does.

    Some programming languages (OOP models) use properties for the same idea. If your public interface only consists of code, you can change the inner workings at any time leaving the interface (and other code which is using it) intact. If your public interface contains data, you restrict your future development possibilies.

    0 讨论(0)
提交回复
热议问题