Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: OOP: How to (not) lose Encapsulation

by jeffa (Bishop)
on May 12, 2015 at 22:48 UTC ( [id://1126475]=note: print w/replies, xml ) Need Help??


in reply to OOP: How to (not) lose Encapsulation

"Composition_over_inheritance" was the mantra that i learned back in 1998 when i attended my first advanced OO class in college. The bad news is that it took me nearly 10 years to understand. :) The good news is that packages like Moose make all of this easier to implement than not. Need to define an interface?

package My::Abstract::Interface; use Moose::Role; requires qw( foo bar baz qux );
instead of
package My::Abstract::Interface; use Carp; sub foo { croak } sub bar { croak } sub baz { croak } sub qux { croak }
If you think about, this is a form of encapsulation itself -- by making it easier to define a proper abstract interface, coders are more tempted to pick the easier-to-code-and-maintain version. Moose (et. al.) make it very easy to delegate and aggregate, without resorting to inheritance:
#!/usr/bin/env perl package Foo; use Moose; has string => ( is => 'rw', isa => 'Str' ); sub to_string { shift->string } package Bar; use Moose; has _foo => ( is => 'rw', isa => 'Foo', handles => ['string'] ); around BUILDARGS => sub {my($o,$c)=(shift,shift);$c->$o(_foo => Foo->n +ew(@_))}; sub to_string { uc shift->string } package main; my $foo = Foo->new( string => 'hello world' ); print $foo->to_string, $/; my $bar = Bar->new( %$foo ); print $bar->to_string, $/;
For me, this is actually easier than using inheritance with classic Perl OO.

UPDATE:
Changed arguments to Bar constructor. (Was the same as arguments to Foo constructor.)

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1126475]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2024-03-28 13:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found