Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

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.


Comment on Re: Unlimited chaining (is there a way to detect this?)
Download Code
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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2014-07-10 04:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (199 votes), past polls