in reply to Writing Object-Orientated Module: use of “new” and other methods.

My question is how I should arrange the methods in the module?
There are many ways. I prefer to have my "constructors" (although what commonly is called a constructor isn't really a constructor - Perl has a constructor, and it's called bless) just create and return an object, and nothing else. Initializing the object is just asking for trouble in the long run; specially if you want to use MI.

So, I'd do something like:

package FruitID; sub new {bless {}, shift} sub init { my $self = shift; ... initialize object ... } ... package main; my $testdata = FruitID->new->init("12 bananas");
Note also that I call new as a class method, and I'm not using indirect calls. That will bite you sooner or later as well, as the call is ambiguous.

Replies are listed 'Best First'.
Re^2: Writing Object-Orientated Module: use of “new” and other methods.
by tchrist (Pilgrim) on May 06, 2011 at 02:26 UTC
    Dative invocations are only ambiguous if you do them sloppily; they are not inherently so. This is a myth, an urban legend in Perl culture. It is not true.
    sub new { die "main::new sub called" } sub Foo { die "main::Foo sub called" } # can't use Foo->new here!!!!!!!!!!! $obj = new Foo:: ; print "Got $obj\n"; package Foo; sub new { return bless [] => shift(); }

    That will correctly print out Got Foo=ARRAY(0x7ec91370). There is no ambiguity: you just have to do it right, that’s all. That said, it’s no fun to chain them.

    And by the way, the mechanism you used won’t work in the code above. Your style can be just as buggy as what you’re worried about people doing by using dative syntax. If you don’t want to use the package-quoted dative syntax of new Foo::, you still must use Foo::->new and not Foo->new, because otherwise you’ll still bomb out. Please try it with the commented-out line to see what I mean.

    Avoiding the dative does not avoid the problem. Package-quoting does.

    Here’s another real-world example:
    my $sorter = new Unicode::Collate:: upper_before_lower => 1, preprocess => \&reduce_for_sorting, entry => deQ<<'END_OF_OVERRIDE', |Q| |Q| 005B 006E 002E ; [.0200.0020.0002.0391] # [n. |Q| 005B ; [.0220.0020.0002.0392] # [ |Q| 005D ; [.0225.0020.0002.0395] # ] |Q| END_OF_OVERRIDE ;
    And here’s another:
    state $formatter = new Unicode::LineBreak:: Context => "NONEASTASIAN", ColumnsMax => 80, ColumnsMin => 8, Format => "SIMPLE", SizingMethod => \&tabbed_sizing, TailorLB => [ ord("\t") => LB_SP, LEFT_QUOTES() => LB_OP, RIGHT_QUOTES() => LB_CL, ], ;
    See how nice and legible that is when written that way? And there really and truly is no ambiguity — unlike with your code, where there is.


    PS: I see my stalker is quick to the draw. Yawn!