15.9. Methods
Despite their obvious differences in dispatch semantics, methods and subroutines are similar in most respects. From a coding point of view, about the only significant difference between the two is that methods tend to have fewer parameters[*].
When you're writing methods, use the same approach to layout (Chapter 2), and the same naming conventions (Chapter 3), and the same argument-passing mechanisms and return behaviours (Chapter 9), and the same error-handling techniques (Chapter 13) as for subroutines. The only exception to that advice concerns naming. Specifically, the "Homonyms" guideline in Chapter 9 doesn't apply to methods. Unlike subroutines, it's acceptable for a method to have the same name of a built-in function. That's because methods are always called with a distinctive syntax, so there's no possible ambiguity between: $size = length $target; and: $size = $target->length( ); It's important to be able to use builtin names for methods, because one of the commonest uses of object-oriented Perl is to create new data types, which often need to provide the same kinds of behaviours as Perl's built-in data types. If that's the case, then those behaviours ought to be named the same as well. For instance, the class in Example 15-5 is a kind of queue, so code that uses that class will be easier to write, and later comprehend, if the queue objects push and shift data using push( ) and shift( ) methods: my $waiting_list = FuzzyQueue->new( ); Naming those same methods append( ) and next( ) makes it slightly harder to work out what's going on (as you can't reason by analogy to Perl's builtins): my $waiting_list = FuzzyQueue->new( ); # Load client names... while (my $client = prompt('Client: ')) { $waiting_list->append($client); } # Then rotate the contents of the queue (approximately) one notch... $waiting_list->append( $waiting_list->next( ) ); Example 15-5. A mildly stochastic queue |