tall_man has asked for the wisdom of the Perl Monks concerning the following question:
Another programmer in my shop did something like this, and a third programmer was caught by it when they set the return value of new() into a variable and called a method on it much later in the code.package MaybeADirectoryObject; use strict; sub new { my ($class, $dir) = @_; if(! -e $dir) { print "The directory $dir does not exist\n"; return; } my $self = {}; # Initialize $self using directory here... bless($self, $class); return $self; }
Since I started object-oriented programming with C++, I find it very strange to return an undef from a constructor. I could see calling die and letting the caller handle the exception with an eval block, but returning an undef seems wrong to me.
What do you think?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Should a constructor ever return undef?
by Zaxo (Archbishop) on Jul 11, 2003 at 01:36 UTC | |
by ctilmes (Vicar) on Jul 11, 2003 at 01:39 UTC | |
|
Re: Should a constructor ever return undef?
by IlyaM (Parson) on Jul 11, 2003 at 08:41 UTC | |
|
Re: Should a constructor ever return undef?
by adrianh (Chancellor) on Jul 11, 2003 at 10:26 UTC | |
|
Re: Should a constructor ever return undef? (yes)
by grinder (Bishop) on Jul 11, 2003 at 14:19 UTC | |
by tall_man (Parson) on Jul 11, 2003 at 15:10 UTC | |
by adrianh (Chancellor) on Jul 11, 2003 at 18:32 UTC | |
|
Re: Should a constructor ever return undef?
by Jenda (Abbot) on Jul 11, 2003 at 15:13 UTC |