Visibility of properties and methods

Depending on the language we will have the following possible visibilities:

  • private
    • visible only to the methods of the class itself.
  • protected
    • visible to the methods of the class itself and derived classes.
  • internal
    • visible to all classes in the same namespace, package, or program where the class was defined.
  • public
    • visible to all classes and objects in the class.
    • compose the API (Application Public Interface).

ATTENTION:

Never use the expression “public API” because all APIs are public.
API stands for Public Application Interface.
So we say only API.

Not all languages offer all the possibilities. It should be checked which visibilities are present and which are not in the desired language.
For example, Ruby and Groovy provide private, protected and public while Swift has private, internal and public. On the other hand, Java supports all four forms, internal is the default, defined by the absence of visibility setting, what means that in Java, if we do not define a property or method like private, protected or public then internal will be assumed.

There is a controversy about the protection of the code given by protected, since any derived class (even third party) can access such properties and methods without restriction, hence the lack of support for this visibility by Swift language that replaces it with internal.

In Pascal language, in order to have the expected visibility we must use Strict Private and Strict Protected instead of Private and Protected, because the latter can be accessed by other classes as long as they are defined in the same file or Unit as the class. In Pascal we also have Published that appears in the Delphi properties palette.

Another important issue is that it is impossible to reduce the level of access to a property or method using inheritance. In languages that allow this to be specified, access reduction is generally ignored. For example, Groovy will give you an error while Swift and Pascal will ignore. Thus, it will not be possible to make private a property defined as public in the base class. If this is really necessary, we should use composition rather than inheritance.

Leave a comment