I would like to introduce some arguments that protect "protected" fields in Java: "You may prefer access to members of the base class using protected fields over public access means in a situation where you need to avoid checking the value." However, if this is not the case, then private fields with public access means should be used to complement the sealing.
The principle of getting and setting is to provide verification of the values entered and displayed for a member of the class. However, in OOP languages we operate on objects, not classes. The base class and the specialized class are one object, so it is perfectly normal to access individual members of the class through a protected field.
Consider the following abstract example with a car: - you have a base class Car and a derived class Porshe. - The Car class may have a field of type engine, the value of which is not set in the Cars constructor (perhaps the type of engine is known only after the object is initialized) - You create an object of the Porshe class that contains some logic used to calculate the type of engine using some external data ,
In this example, the engine field is expected to have an open getter, so car users know which engine the car has. However, there is no public setter, as we expect car drivers to not tune in to work with the engine! That's why it's perfectly normal to make an engine a protected field, so the Porshe class can set its value in the future.
Yes, some people will probably say, "Then use a secure setter!" And again I repeat: in OOP languages we work with objects, not with classes. The principle of common responsibility is yes, but as an object, and not as a class. If you say: "at some point, if we use protected fields with 3 or 5 levels of inheritance, it can be difficult to understand what happens to the field if each class performs an operation on it." And then I answer: this is another antipattern - your object is probably too large at the moment and is losing the principle of a single responsibility.
Andrey Borisovich Jan 29 '19 at 13:24 2019-01-29 13:24
source share