In OO languages like C++, Java or C#, there are access modifiers like public
, private
, protected
. Some languages have other modifiers like internal
. All of them specifies who can access a certain variable or method. And for variables, this term access means both the ability to read and modify. But the most common scenario for accessing variable is making it publicly visible to others but keeping the ability to modify within the class. And this is achieved through many tactics using getter setter etc.
My question is, why don't we have a access modifier for the most common scenario, which can be named something like visible
? Then the variable marked with it can be read by external classes or methods. But can only be modified within the class.
Your suggestion would encourage the implementation detail of how the state is represented within the class to be made public.
Using one level of indirection - properties - allows you to separate out the public API of a type from its implementation. That can be of great benefit:
I'm all for languages making it easier to expose read-only state (as C# 6 is doing with read-only automatically implemented properties, for example) but I wouldn't encourage the fields themselves to become more visible.
See more on this question at Stackoverflow