JavaRush /Java Blog /Random EN /Getters and broken encapsulation
Vadelic
Level 14
Пасадена

Getters and broken encapsulation

Published in the Random EN group
While solving problems, I encountered unexpected behavior of getters. In the lectures here and even in the getters generated by IntelliJ IDEA, the simplest scheme is used: public final class A { private A field; public A getField() { return field; } public void setField(A field) { this.field = field; } } If the field is a primitive type or String, which is passed by value, then everything is fine, but if the object is passed by reference, then it turns out that through the getter you can get full access to the field , which nullifies the set protected access level. If the setter contains any validity condition, then it can be bypassed through such a getter, which violates encapsulation and it would be correct to create a clone of the object to avoid this trouble. I understand that not all objects can be easily cloned, and if this is left to the responsibility of the programmer, then it’s strange why there was no mention of this anywhere in the lectures. UPD: A getter, as an idea, of course, does not violate encapsulation, but it must be written in such a way as not to betray the principles of OOP. This means that if a getter produces an object, it does so in such a way that the user cannot change it in any other way that is specified in the class. There is a wonderful method in the Collections class that produces a read-only collection. This imposes a number of other restrictions, for example, the impossibility of sorting, but for this case this class has: unmodifiableSortedSet unmodifiableSortedMap and a few more, for greater convenience. public static Collection unmodifiableCollection(Collection c)
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION