Perl6 Object Oriented Cookbook (v0.2.1)  
Section 2: Attributes and Methods  
 
Recipe 2.9: 'Finalizing' the Interface/Signature/Prototype of a Method
Last Updated: Sep 8, 2003
Status: Likely
      Previous Page   Next Page

How important is this problem to you?
  (Login to Vote)
5.00 Rating, 3 Votes  

How acceptable is the proposed solution?
  (Login to Vote)
5.00 Rating, 2 Votes  

Problem:  

You want to prevent subclasses -- or anyone else -- from changing the interface of a method. In other words, you want all implementations of the method, in all subclasses, to match the same method signature.

Solution:  

Use the is interface property:

method foo(...) is interface;         # an 'abstract' interface: has no implementation

method bar(...) is interface { ... }  # or give a default implementation

Discussion:

In perl5, methods of a class (package) were rather squirrely things. When you overrode a parent's method in a subclass, you just overrode it: it was up to you to verify that the signatures of the two methods matched, if you wanted them to. This older philosophy is still available, and is in fact still the default behavior of methods.

In perl6, the concept of interface methods is more explicitly supported. The is interface property is used to enforce a "permanent" signature for a method. Subclasses may alter the implementation of a method, but each implementation must conform to the method signature already given; if an attempt is made to assign an implementation to a method that does not match the interface signature, an exception is thrown.

It is especially useful to assign the is interface property to abstract methods (methods that do not yet have an implementation): this allows you to specify that all possible implementations of a method must conform to the declared method signature.

If you want to be able to change the signature of a particular method in subclasses, no problem: just declare it the normal way, without is interface.

As a special case, it is always allowable to add extra, optional arguments to an overriden interface. This allows individual subclasses to define "more detailed" behavior of an interface method -- behavior that other subclasses don't need to know about.

Issue: Should there be an optional 'strict'ness that implies all methods in all classes are interface methods, without having to say it in every class?


Log In to Comment


Login / Edit User Info -- Copyright © 2002 Cognitivity -- Previous Page   Next Page