Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: Mutator chaining considered harmful

by fizbin (Chaplain)
on Dec 29, 2004 at 22:18 UTC ( [id://418106] : note . print w/replies, xml ) Need Help??

in reply to Mutator chaining considered harmful

(Pulling this from the cb)

You know, there's only one place where I've come to think that self-chaining of mutators is a good idea, and that's in things like java's StringBuffer.append: basically, when the manipulator method is an accumulator of some sort.

So I've seen self-chaining, for example, in a C++ class that did checksums:

Checksum myCS; myCS.addTo(x).addTo(foo).addTo(barObject); cout << myCS;
Or the more familiar: (again, C++)
cout << "Value is: " << dec << myValue << " (hex: " << hex << myValue +<< ")";
Here "dec" and "hex" aren't manipulators in the same sense as above, quite, but the syntax is clearly very similar. Again, though, the sense is that << is acting as an accumulator, and what passes through it adds on to what was there before, instead of being a "setter" method.

So getting back to Perl, this is in my opinion a perfectly respectable interface for a file-parsing library:

my $Ifile_format = new What::Ever::Format(); $Ifile_format->addRecType($XErec) ->addRecType($XFrec) ->addRecType($I7rec) ->addRecType($HMrec);
In this case, addRecType, while changing the state of $Ifile_format, is adding on new potential record types, and not setting some distinct value.
-- @/=map{[/./g]}qw/.h_nJ Xapou cets krht ele_ r_ra/; map{y/X_/\n /;print}map{pop@$_}@/for@/

Replies are listed 'Best First'.
Re^2: Mutator chaining considered harmful
by Anonymous Monk on Dec 30, 2004 at 09:37 UTC
    Or to stay closer to home, Perl's 5.9.x stacking file operators:
    if (-r -w $file) { # File is readable and writeable ... }

      I don't think those are stacked, exactly. I think they use the syntax of single-letter command-line options.


Re^2: Mutator chaining considered harmful
by simonm (Vicar) on Dec 30, 2004 at 21:10 UTC
    Echoing the point made in the updated OP, wouldn't it be better to create a method that let you do that all at once?
    $Ifile_format->addRecTypes($XErec, $XFrec, $I7rec, $HMrec);
Re^2: Mutator chaining considered harmful
by Aristotle (Chancellor) on Jan 04, 2005 at 19:11 UTC

    “For the record,” I agree. I originally ++ed this node but for some reason never commented.

    Makeshifts last the longest.