in reply to Re: new() function: incorrect?
in thread new() function: incorrect?

I must admit that whenever I've been coaching people on creating new objects, I almost always tell them to declare an object like this:
my $objectBlah = Blah::Object->new();
I guess my reasoning behind this is that you should always be clear on creating a new instance of an object. I can't think of too many instances where I'd do
my $foo = $bar->new();
...that just wouldn't, generally, cut the mustard with me -- unless you *really* needed another instance of the same object to do other stuff with. As I write this, I was trying to think of when I've needed to do this exact thing, and I honestly can't think of any instances that I've done that.

However -- that may merely be an indictment of how I like to design my objects and code, generally.....!

Also, I, personally dislike the following syntax:
my $foo = new Bob::Object;
I can't think of an exact reason -- probably just that I think that perl's syntax is nearly always based around using something like (in the case of reading a constant item that you've set up in your object framework) :-
my $constantStuff = Bob::Constants::CONSTANT_STUFF;
Adding in something like this:
my $bob = new Bob::Object;
...just doesn't fit (in my head at least) with the nice perl way of doing things.

I know my reason doesn't make too much sense: I just like a bit of consistency........!

PS I'm actually really enjoying this conversation about something as simple as the best new() function to use. It reminds me of why I love perl so much.......!

Replies are listed 'Best First'.
Re^3: new() function: incorrect?
by gone2015 (Deacon) on Nov 12, 2008 at 15:38 UTC

    I wouldn't recommend:

    $obj->new(...) ;
    either. And, if I ever wanted to have a new object of the same class as another I'd prefer:
    ref($obj)->new(...) ;
    because (once you've worked out WTF is happening) it says exactly what is intended.

    However, on the general basis "Be strict in what you send, but generous in what you receive", throwing a run-time error at $obj->new(...) strikes me as ungenerous. Noting that perlobj for 5.10 (and 5.8.8) describes how to cope with this eventuality -- as the fourth in a sequence of increasingly complete object constructors.

Re^3: new() function: incorrect?
by lukeyboy1 (Beadle) on Nov 12, 2008 at 15:02 UTC
    Or even:
    Bob::Object::new();
    to correct my last example. It's a method, so deserves the use of -> as far as I'm concerned.

    \end belligerent rant! :)