Syntactic Confectionery Delight | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
Hello tiny_monk, The moment I saw $self->{'key'} = shift; being used in the setter and $self->{'key'} in the getter functions, it gave me the notion that the encapsulation was being broken. But I may be wrong. My understanding is that the object's innards should stay inside the object. You are absolutely right, an object’s implementation (“innards”) should stay private to the object, to maintain encapsulation. But getter and setter methods are internal to the object — or, rather, they are internal to the class from which the object is instantiated. So it is quite appropriate for them to access the object’s innards. Encapsulation is broken only when an object’s implementation details are exposed or accessed outside the object. While I understand that it is not advised that an API caller use $self->{'key} to access or update the object's attribute outside a class, ... In this context, an object’s “API” is equivalent to its “interface”, that is, the totality of its public methods. And since the object itself is a blessed reference, it is often possible for code with access to the object to access its innards directly. But that breaks encapsulation, so external code should access an object only through its public methods. In your original example, the methods set_color and get_color do not break encapsulation, because they are defined within package Fruit. But suppose we add the following lines:
The output is now:
which shows that we have again altered the apple’s colour. But this time we have done so by accessing the object’s internals directly, which does break encapsulation. Unlike other OO languages, Perl allows this to happen, but that doesn’t make it a good idea! Here’s a famous quote from Larry Wall: Perl doesn’t have an infatuation with enforced privacy. It would prefer that you stayed out of its living room because you weren’t invited, not because it has a shotgun. But there are also techniques for enforcing privacy. See the section “Using Closures for Private Objects” in Chapter 12 of the Camel Book (4th Edition, 2012, pp. 446–9), and modules such as MooX::ProtectedAttributes for use with Perl object systems such as Moose and Moo. Hope that helps,
In reply to Re^3: OOP's setter/getter methods - is there a way to avoid them?
by Athanasius
|
|