[Pdx-pm] Changing contructors w/o breaking compat.

Randal L. Schwartz merlyn at stonehenge.com
Fri Oct 25 23:44:15 CDT 2002


>>>>> "Joshua" == Joshua Hoblitt <jhoblitt at ifa.hawaii.edu> writes:

Joshua> I was using Net::Ping the other day and became irritated with the contructor.  It would be fairly simple to just subclass it and add a own contructor but it got me thinking about how one would update the contructor and not break legacy code.
Joshua> These are the first few lines of the constructor for Net::Ping.  Not only would it be much "prettier" to use a hash in the contructor there are several settings with must be set via a method call.  Of course I could just wait for perl6 then test 2nd param to see if it is a scalar or a slice but I'm assuming there must be some clever way of dealing with this now.

Joshua> sub new
Joshua> {
Joshua>   my ($this,
Joshua>       $proto,             # Optional protocol to use for pinging
Joshua>       $timeout,           # Optional timeout in seconds
Joshua>       $data_size,         # Optional additional bytes of data
Joshua>       $device,            # Optional device to use
Joshua>       ) = @_;
Joshua> .
Joshua> .
Joshua> .

sub new {
  my $self = shift;
  my %param;
  if (ref $_[0] and ref $_[0] eq "HASH") { # damn warnings
    %param = %{+shift};
  } else {
    @param{qw(proto timeout data_size device)} = @_;
  }

  ...
}

Old style new:

        my $object = Net::Ping->new($proto, $timeout, $data_size);

New style new:

        my $object = Net::Ping->new({proto => $proto, device => $device});

It's been done before.  Not sure where I saw it.

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn at stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!



More information about the Pdx-pm-list mailing list