Whether or not you use an '_init' method is really just matter of styleI strongly disagree with an '_init' method just being matter of style. That's like saying "Whether or not a language has hashes is just a matter of style".
Suppose you have classes with the following new methods:
And now you need to create something that's both a DessertTopping and a FloorWax, using two corner stones of object oriented programming: code reuse and encapsulation.package FloorWax; sub new { my $class = shift; bless {FW_massage(@_)}, $class; } package DessertTopping; sub new { my $class = shift; bless {DT_massage(@_)}, $class; }
Sure, the start is easy:
But then what? Without breaking encapsulation, how do you set up the object so it's both a FloorWax, and a DessertTopping? If you call FloorWax->new you get a configured FloorWax object, without the DessertTopping attributes. And if you call DessertTopping->new, you will be missing the FloorWax attributes.package FloorToppingDessertWax; our @ISA = qw[FloorWax DessertTopping]; sub new { my $class = shift;
If instead, you had:
Things would be a lot easier. You could write a derived class as:package FloorWax; sub new {bless {}, shift} sub init { my $self = shift; my %arg = FW_massage @_; @$self{keys %arg} = values %arg; $self } package DessertTopping; sub new {bless {}, shift} sub init { my $self = shift; my %arg = DT_massage @_; @$self{keys %arg} = values %arg; $self }
package FloorToppingDessertWax; our @ISA = qw[FloorWax DessertTopping]; sub new {bless {}, shift} sub init { my $self = shift; foreach my $class (@ISA) { my $init = "${class}::init"; $self->$init(@_) if $self->can($init); } $self; }
So, I argue that having or not having an _init method isn't a matter of style. Having an init (not really an _init, as it should be called from the outside) makes your class more (re)usable.
In reply to Re^2: Philosophy of a "new" method
by JavaFan
in thread Philosophy of a "new" method
by rastoboy
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |