I am writing a simple Perl module that handles time and date information. Below is a simplified version of the constructor and one of the accessor methods:
package Time;
# Constructor
sub new {
my $class = shift;
my %args = @_;
# Create an empty object
my $self = bless {};
# Get input arguments
my $second = exists $args{'second'} ? $args{'second'} : (localtime)[0];
# Use the accessor to validate and populate object data
$self->second($second);
return $self;
}
# Second accessor
sub second {
my $self = shift;
my $second = shift;
# Input validation
if (defined $second) {
if ($second =~ m{^\d+$} && $second >= 0 && $second <= 59) {
$self->{'second'} = $second;
}
else {
die "'second' must be an integer between 0 and 59!";
}
}
return $self->{'second'};
}
My question is... Is it acceptable to use an accessor in object construction in Perl?
Using the accessor inside of the constructor makes it so I don't need all of the validation code in the constructor itself since the input is validated by the accessor, but is this bad practice?
Is there any reason I would not want to do this?