in reply to Method Chaining and Accessors

While chaining is neato and all, I can't think of a good reason to support this use. What's wrong with simply passing a hash of configuration information to your constructor? This seems far more reasonable to me:

my $obj = My::Class->new( foo => 'foo', bar => 'bar' );

Under the hood, your constructor can either modify the object directly or call the accessors/mutators and let them do the work.

Replies are listed 'Best First'.
Re^2: Method Chaining and Accessors
by f00li5h (Chaplain) on Apr 05, 2007 at 02:03 UTC

    The client can pass silly things in the hash, and the writer of the class has to validate that all required keys are present, and extranious ones cause warnings. unless you have Class::Std do it all for you.

    (and to be pedantic, you're not passing a hash at all)

    Update I forgot to mention that I did actually agree with the "passing data to the constructor" idea.

    @_=qw; ask f00li5h to appear and remain for a moment of pretend better than a lifetime;;s;;@_[map hex,split'',B204316D8C2A4516DE];;y/05/os/&print;
      Class::Std is definitely worth a look-see. It automates a lot of the messiness you (the OP) are trying to avoid.

      cat >~/.sig </dev/interesting

Re^2: Method Chaining and Accessors
by grinder (Bishop) on Apr 05, 2007 at 07:34 UTC
    While chaining is neato and all, I can't think of a good reason to support this use.

    I can. Lots. There's many a time you can't stuff everything into a constructor, and then live with the object ever after. Sometimes you have to twiddle the object repeatedly during the life of the program. In that context, method chaining usually results in more compact, clearer code.

    Take a look at this review of HTML::CalendarMonth, which is an example of where I think chained methods would be a big win.

    • another intruder with the mooring in the heart of the Perl

Re^2: Method Chaining and Accessors
by jhourcle (Prior) on Apr 05, 2007 at 19:45 UTC
    While chaining is neato and all, I can't think of a good reason to support this use. What's wrong with simply passing a hash of configuration information to your constructor?

    Besides what grinder has already mentioned, there's an inability to force the order of the operations.

    For instance, in SOAP::Lite, there are some settings (eg, 'service') that affect mutliple parameters, so I need to ensure that they're called first, and then the ones I want to individually override.

    Now, in your case, you passed a list, so the method could just splice off the front and make sure they were applied in the correct order -- if you had used a hash, that wouldn't have been possible.