I have inherited some old Perl 5.8 code. It is a straightforward, old-fashioned Perl OO module, more "object based" than "object oriented" in that there is no inheritance.
I noticed some of the "instance methods" are not really instance methods in that though they start with my $self = shift they do not actually use $self in the function body. That is, the class is a mixture of instance methods (related to the class and using object state) and utility functions (not really related to the class and not using object state). The user of the class currently calls both these different types of functions in the same way, via the object handle, for example:
my $obj = MyPackage->new("..."); # ... my @some_list = $obj->some_method("some string");
I seem to have three options:
To illustrate with some sample code, here is MyPackage.pm:
And here is a sample program that calls into this package:package MyPackage; use strict; use warnings; sub new { my $class = shift; $class eq __PACKAGE__ or die "oops: ctor unexpected '$class'"; my $name = shift; print "in ctor: '$class' (name=$name)\n"; my $self = {}; $self->{NAME} = $name; bless $self, $class; return $self; } sub some_instance_method { my $self = shift; my $param1 = shift; print "in some_instance_method: $self '$param1'\n"; return $self->{NAME}; } sub some_class_method { my $class = shift; my $param1 = shift; print "in some_class_method: '$class' ($param1)\n"; $class eq __PACKAGE__ or die "oops: unexpected '$class'"; return "hello from some class method"; } sub some_utility_method { my $param1 = shift; print "in some_utility_method: ($param1)\n"; return "hello from some utility method"; } 1;
use strict; use warnings; use MyPackage; my $obj = MyPackage->new("John Smith"); my $name = $obj->some_instance_method(69); print "name='$name'\n"; my $cm = MyPackage->some_class_method(42); print "cm='$cm'\n"; my $um = MyPackage::some_utility_method(43); print "um='$um'\n";
Running the sample program above produces:
in ctor: 'MyPackage' (name=John Smith) in some_instance_method: MyPackage=HASH(0x1c905b0) '69' name='John Smith' in some_class_method: 'MyPackage' (42) cm='hello from some class method' in some_utility_method: (43) um='hello from some utility method'
In reply to How to deal with old OO code that mixes instance methods with class methods by eyepopslikeamosquito
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |