As well noted in the question, the "Open/close" principle of "SOLID" may go against the use of members of global or public scope (public
in most languages).
What says the principle of "Open/close"?
In Object-oriented Programming, the open-closed principle States
"software entities (classes, modules, functions, etc.) should be open
for Extension, but closed for modification"
Source: https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle
In free translation:
In object-oriented programming, the open-closed principle states
"software entities (classes, modules, functions, etc.) must be
open for extension, but closed for modification"
First let’s look at your example:
clients.forEach((e) => usernames.push(e.username)); //Acessando variável fora do escopo
What matters is, to respect the principle of Open/close, we must ensure that this method can be extensible, but not change "modify the original" so to speak.
If we extend this method and can change the variable clients
, this may affect the behavior of other components that use this variable, because it has a larger scope than the method or class, so we would violate the principle.
Since it is a countant, there is no possibility of it being changed, so in his case This adheres to the principle.
As @Cmtecardeal had commented, if a member has a scope outside the class, it is because we want to share between various parts of the code, then he must be immutable, a constant for example, possibly static when possible, but the most important thing is that they do not allow change. Note that, the fact that it is simply static
does not guarantee that it cannot be changed, it is necessary to protect using a const
or with encapsulation.
Classes with Resources are a good example, for example messages and strings that are used within the entire application, which must be constant.
Therefore, it is not accessing the variable that goes against the principles, but the variable allowing changes, being of scope outside the class is who would go against the principle.
As I’m running out of time to answer, I’ll comment on what I’ve learned. The recommendation is that one should avoid using global var, as it may be difficult to ensure that other modules, classes, functions, etc... will not modify this global var. However, I have read in articles that you can use global var, as long as these are static, that is, read only and that are not possible to be modified... I could be wrong, but I’ll wait for someone more expert to talk about it in the answers.... I think their use would be infringing the
S
and/orO
of SOLID.– Cmte Cardeal