http://qs321.pair.com?node_id=11137390


in reply to Re: OO Pattern Container x Elements and Method Chaining (House, Person, Inhabitant)
in thread OO Pattern Container x Elements and Method Chaining

In 25 years of programming I have never actually run into a case where an element needed to know its container and also belong to multiple containers. *shrug*

In most cases I’ve had where the element knew about its container, it was created and owned by the container, so there was no way to create it independent from the container, and the container was free to choose whether the element would be persistent using weak references, or temporary and only held by the strong reference given to the caller when they retrieve the object.

If you have a sub X that needs to know about 2 objects, A and B, and A seems like a logical “container” and B seems like a thing that ought to be contained, then I would make A’s “get_B” return a temporary object C which holds strong references to A and B and has X as one of its methods.

package A; use Moo; has ‘b_set’, is => ‘rw’; sub get_b($self, $name) { return C->new(a => $self, b => $self->b_set->{$name}); } package B; use Moo; sub do_thing_with_a($self, $a) { … } package C; use Moo; has ‘a’, is => ‘ro’; has ‘b’, is => ‘ro’, handles => [qw( … )]; # all of b’s methods sub do_thing($self) { $self->b->do_thing_with_a($self->a); }