Using Closures for Private Objects
So far, these techniques for managing instance data have offered no mechanism for “protection” from external access. Anyone outside the class can open up the object’s black box and poke about inside—if they don’t mind voiding the warranty. Enforced privacy tends to get in the way of people trying to get their jobs done. Perl’s philosophy is that it’s better to encapsulate one’s data with a sign that says:
IN CASE OF FIRE BREAK GLASS
You should respect such encapsulation when possible, but still have easy access to the contents in an emergency situation, like for debugging.
But if you do want to enforce privacy, Perl isn’t about to get in your way. Perl offers low-level building blocks that you can use to surround your class and its objects with an impenetrable privacy shield—one stronger, in fact, than that found in many popular object-oriented languages. Lexical scopes and the lexical variables inside them are the key components here, and closures play a pivotal role.
In the earlier section Private Methods, we saw how a class can use closures to implement methods that are invisible outside the module file. Later, we’ll look at accessor methods that regulate class data that are so private not even the rest of the class has unrestricted access. Those are still fairly traditional uses of closures. The truly interesting approach is to use a closure as the very object itself. The object’s instance variables are locked up inside a scope to which the object ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access