|Don't ask to ask, just ask|
use fields; # damnitby nothingmuch (Priest)
|on Aug 20, 2004 at 20:39 UTC||Need Help??|
Every time I bring this up people say I'm bonkers. Here goes.
Occasionally Perl's OO system is bashed, because it's too lax, which is true in some respects. I guess the most sensible answer is "wait for Perl 6", or "use Java" for most arguments. That's what I hear, more often than not.
What I'm bringing up is one aspect of strictish OO that is handled in Perl. This is compile time field (properties, instance data) checking. What? compile time? Yes, fscking compile time, I'm not lying.
The fields pragma is, as far as I know, the least used useful module out there. This post is nothing but advocacy for it. Improperly used, it gives you no real benefits, except the implicit use of depracated features (pseudohashes), under Perl 5.8.
However, if you do all the steps you need to get the benefits, you end up with something pretty powerful, especially if you're a lousy typist, or can't read very well.
Say you are implementing a Dog. Some dogs are stupid. You might start out with something like this:
And then you add a method:
Presto. You have a dog class. Now lets create $lassie. She is intelligent, right?
Whoops. Warnings would help, but strict wouldn't. Anyway, you get the point. I typoed the field name, and everything broke. I could be pecking for hours, looking for that.
So lets get a little formal, and say what we define:
So where does that get us? Well, nowhere. If you use base qw/Dog/ somewhere, the subclass would get that field, but that doesn't concern us now. Otherwise it's just a silly way to bless your $self.
The problem is that there's a general myth about fields, that that's all you're supposed to do, and that because it doesn't work, and to top it off uses pseudohashes, fields is bad. Both statements are false (the conclusion might not be, decide for yourself). Regarding the phashes, since 5.9 fields uses restricted hashes. The interface didn't change. In the future, fields might be implemented completely differently, and at the bottom line that's the point. You're not supposed to care that it uses phashes, because the phashes are hidden behind the usage interface.The other issue, well, we're getting there.
Lets move on to the my variable declaration. Notice that my TYPE $var syntax thingy? Well, it lets you tell perl that $var will be of class TYPE.
Aha! so If we do
presto, we've got compile time field checking. If it were only a bit more concise, that could be really fun, but what does it matter. Go home and start using it.
Update: grammer fixes.
zz zZ Z Z #!perl