in reply to Beginner OOP style question
First of all, welcome to Perl OO. Don't let the whiny Java-apologists or Python-huggers convince you that Perl's OO model is broken. It may not suit their aesthetic tastes, but I happen to really enjoy the flexibility it offers.
To answer the question itself first, can you implement the search method without having an actual object reference? It sounds like you have already drawn that conclusion, since you perceive the creation of an object for the sole purpose of calling the method to be wasteful. So let me introduce you to the static method, also known as the class method.
A static (or class) method is one that does not use an actual instance of an object in its operation. You will often see them in code or in examples within books, being called something like:
$req = Apache->request();
Note that what you see is a method call-- it is calling the request() method of the Apache class. But there is no need for an object in order to call this. So instead, the class name itself is used.
Another common example is the constructor. You're probably already using it as a class method. You are probably coding something akin to:
my $new_human = new Person (name => 'Bob'); # Always 'Bob'...
If you do, be aware that TheDamian may set aside a dunce cap especially for you. He doesn't like that syntax, and I personally have come to appreciate the more-clear:
my $new_human = Person->new(name => 'Bob'); # Still 'Bob'...
Your method code must still shift a first argument off the list-- the argument is still there, it's just that it's a string literal ('Person' in this case) rather than a reference. I've written a lot of OO Perl, and every class I've written has had at least 3 or more class-methods. They're as much a part of a package as constants and the inclusion of other libraries.
On the topic of your search() method, I would recommend a change, however. There is no point in giving a list of integers back to your caller. What is he or she supposed to do with them? Return a list (or better, a list reference) of objects. Returning a list reference keeps the method in a scalar context, and it's easier to discern a successful return versus an error (which would be either undef or an error string, both singular values).
Lastly, I cannot recommend Damian's book, Object Oriented Perl, highly enough. Everyone I know who has read it, regardless of their level of Perl expertise, has taken away something useful from it. It is as valuable an investment in your library as the Camel book.
--rjray
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Beginner OOP style question
by Tardis (Pilgrim) on Mar 02, 2002 at 08:39 UTC | |
by jeffa (Bishop) on Mar 02, 2002 at 13:21 UTC | |
by fuzzyping (Chaplain) on Mar 02, 2002 at 13:37 UTC | |
by Anonymous Monk on Mar 02, 2002 at 20:49 UTC |