What Else a Method Keyword Could Do

| 2 Comments

Suppose someone applied a patch to add the method keyword to Perl 5. The benefits could go far beyond the simplicity of intent and implementation you get from writing:

use feature 'method';

method do_awesome_things
{
    $self->do_something;
    $self->do_another_thing;
    $self->do_yet_another_great_thing;
}

Sure, you save one line per method and you've communicated your intent that do_awesome_things() is really a method. (The argument "Can't you just put a comment or POD somewhere saying that do_awesome_things() is a method?" is exceedingly silly. You might as well use goto for all of your control flow. After all, you can always add a comment # this is a while loop.)

With method, you've done more than communicate to programmers that your method is a method. You've told Perl itself that your method is a method, and Perl can do many, many new things with that information. If Perl somehow marked the internal data structure it creates to represent methods (whether setting a flag or extending its CV structure with a MV structure), it could distinguish between functions and methods. This would allow several useful new features, not limited to:

  • Perl could detect the invocation of a method as a function and give a warning (which you could promote to an exception with use warnings)
  • Perl could fix the SUPER problem
  • Perl could add an API to namespaces to retrieve the names of only the methods in a namespace
  • If Perl 5 had a class keyword, it could compile the class, resolve all of the uses of functions within the class, then remove functions from the class's namespace to leave only methods, so as to avoid inadvertent namespace pollution with non-methods. See also namespace::autoclean.

You get these benefits by adding this feature to the Perl 5 core. You can sort of emulate some of them with CPAN distributions—but in the core, you can make the need for some distributions and big chunks of features of some distributions disappear. Some flaws you can only truly fix within the language itself, and not in its ecosystem.

2 Comments

Oops, looks like you forgot the close anchor tag on "the SUPER problem"

I hope this makes it into Perl 5.16 at the latest.

Modern Perl: The Book

cover image for Modern Perl: the book

The best Perl Programmers read Modern Perl: The Book.

sponsored by the How to Make a Smoothie guide

Categories

Pages

About this Entry

This page contains a single entry by chromatic published on January 21, 2011 10:44 AM.

Adding a Method Keyword to Perl 5 was the previous entry in this blog.

The Little Conveniences is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.


Powered by the Perl programming language

what is programming?