abra
abra

Reputation: 575

Perl - chaining method calls

I have a class and want to chain its methods calls in strict order, but can't figure out how to do it.

# Mail.pm

package Mail;

sub new { ... }
sub inbox { ... }
sub folder { ... }
sub count { ... }

1;

and later ...

use Mail;

my $mail = Mail->new;

# ok
$mail->inbox->count;
$mail->folder('Spam')->count;

# prevent calling inbox() after folder() or vice versa
$mail->inbox->folder('Spam')->count;
$mail->folder('Spam')->inbox->count;

Upvotes: 1

Views: 1133

Answers (1)

Sinan Ünür
Sinan Ünür

Reputation: 118148

Clearly, folder should return a My::Mail::Folder object which has a count, and no inbox method, and inbox should return a My::Mail::Box object which has a count method, but no folder method.

On the other hand, I am not sure why $mail->inbox->folder('Spam')->count; is problematic.

On the other other hand, why are you attracted to method chaining?

Also, keep in mind that there are a whole bunch of CPAN modules under the Mail:: namespace including Mail::Box, and it might help your sanity in the long run to put things in a namespace that is less likely to be trampled on by a CPAN module you might need.

Upvotes: 7

Related Questions