leocharre has asked for the wisdom of the Perl Monks concerning the following question:
I've read off and on that when you make an object oriented package, that you should not force poop on people. That it should be an opton, not a default.
So, my first thoughts were ... I guess if my package has method hello(), then there should be a _hello() which is the functional oriented equivalent. Seems silly.. And I have a gut feeling there's various tricks to have a sub act as both a functional oriented, and object oriented subroutine.
I patched this together and it seems to work well. Here's my example:
use Carp; use constant haveyaml => ( eval 'require YAML;' ? 1 : 0 ); my $META_HIDDEN=1; sub META_HIDDEN : lvalue { $META_HIDDEN } my $META_EXT = 'meta'; sub META_EXT : lvalue { $META_EXT } sub set_meta { my $abs_path = shift; if (ref $abs_path eq __PACKAGE__){ $abs_path = $abs_path->abs_path; } my $meta = shift; ref $meta eq 'HASH' or croak('second argument to set_meta() must be a hash ref'); haveyaml or carp 'set_meta() cant be used, ' .'YAML is not installed.' and return; $abs_path=~s/^(.+\/)([^\/]+$)/$1.$2/ if META_HIDDEN; unless( keys %$meta){ unlink $abs_path .'.'.META_EXT; return 1; } YAML::DumpFile($abs_path .'.'.META_EXT,$meta); return 1; }
So this sub can be used as $object->set_meta($hashref) or set_meta($path,$hashref). The way to detect here is to see if the first argument is a ref to the package, or not.
I've looked for examples of having subroutines act as both object oriented and functional oriented code, and I came up kind of empty, maybe I'm not looking right.
Any suggestions how else to do this? How to have a subroutine detect if it's being used as a method or a normal subroutine?
And uhm.. If I can also ask.. Is setting that constant to check for YAML really bad? Or too taxing on the sytem?
update
Using a subroutine as both procedural function and oo method can create problems with inheritance (and complexity). Thanks to the discussion, I can with confidence put this aside and move on. Verdict is nonono. I'll use different subs, some for oo some for procedural.
|
|---|