Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re: Unlimited chaining (is there a way to detect this?)

by rafl (Friar)
on Jan 05, 2008 at 23:48 UTC ( #660593=note: print w/replies, xml ) Need Help??

in reply to Unlimited chaining (is there a way to detect this?)

You could store a flag in each object created by the bar method and check that in bar.

#!/usr/bin/perl -w use strict; package BaseClass; use strict; sub new { my $class = shift; my $self = {}; bless $self, $class; $self; } sub bar { return Foo->new; } package Foo; use strict; use Carp; use base qw(BaseClass); sub baz {"Some data"} sub bar { my $self = shift; warn "bar"; croak "don't chain method calls" if $self->{chained}; my $ret = $self->SUPER::bar(@_); $ret->{chained} = 1; return $ret; } package main; use strict; my $o = Foo->new; print $o->bar->bar->bar->bar->bar->bar->bar->bar->bar->bar->bar->bar-> +bar->bar->baz; __END__ bar at -e line 1. bar at -e line 1. don't chain method calls to bar at -e line 0

Unfortunately that breaks encapsulation, but maybe your baseclass provides an api to do it cleanly.

Replies are listed 'Best First'.
Re^2: Unlimited chaining (is there a way to detect this?)
by Burak (Chaplain) on Jan 06, 2008 at 20:38 UTC
    Yes can be. But this does not work if new() uses a scalar (which is what I did after realising that I don't really use the underlying hash):
    sub new { bless \do{my $anon_scalar}, shift }
      Why not? No one forces you to store the flags (in this case) in the object itself.

      Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://660593]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (3)
As of 2018-04-22 17:04 GMT
Find Nodes?
    Voting Booth?