leocharre has asked for the wisdom of the Perl Monks concerning the following question:
I'm trying out an interesting practice.
When I code OO, first I code 'would be methods' as functions only, in a separate package. And use tests to check them out.
Later I can code a OO interface, which makes use of those functions.
Example.
Let's say I have Cleaning.pm
I have Cleaning::Functional::sweep() and Cleaning::Functional::vacuum() subroutines that can be exported. These take a few parameters and options via a hash ref, room of the house, maybe the kind of floor, etc.
I also have an OO interface, via which I can clean a whole house without telling each function every freaking parameter each time (amongst other OO pros). So I have Cleaning::OO::new(), via which I can have $object->vacuum(), $object->sweep(), etc. (I want to emphazise that the OO interface is not a rewrite of the functions!)
Cleaning::OO, imports Cleaning::Functional subs.
The following is imaginary code (this is a lose example):
I think this has been helping me test better, and code better OO.package Module::Functional; # functional # the more complex operations and logic would happen here sub clean_to_level { my ($cleanliness_now, $target_cleanliness) = @_; while( $cleanliness_now < $target_cleanliness ){ $cleanliness_now++; } return $cleanliness_now; } 1; package Module::OO; use Module::Functional; # oo version # this package would in great part be an interface to the other packag +e. sub clean_to_level { my ($self,$target_cleanliness) = @_; $target_cleanliness ||= $self->default_target_cleanliness; return Module::Functional::clean_to_level( $self->cleanliness_now, $target_cleanliness, ); }
Here's my questioning.
Having Module::Functional::run() and Module::OO::run() looks creepy (?). Giving either (style/programming philosophy/methodology?) the prime namespace real estate over the project seems biased- and misleading! As if it hints that you should use one over the other.- And then, I really want the functional run() and the oo $o->run() to have the same sub name, obviously slightly different doccumentation- and if they reside in the same package... This would be like.. CGI.pm (?)
(CGI.pm for example- you can use the calls as subs or methods.
I've looked through CGI.pm- and it makes me feel like a drunken sailor at a strip joint. Way over my head.)
I want the code to be able to be used as both functional or OO. I foresee myself and others wishing to use the code- to want to use both on occassion. The OO stuff is much more friendly to use in a larger program, the functional is much more easy to recycle ( my personal feelings about what I code ).
So far, I've been alright by using separate packages to accomplish this.
What about using one package like in CGI.pm? That can be used both ways, if you call import tags, it does so.. if you call new, you're in oo mode.. etc.
|
---|