What is the difference between new Some::Class and Some::Class->new() in Perl?

后端 未结 4 1712
我在风中等你
我在风中等你 2020-11-29 08:27

Many years ago I remember a fellow programmer counselling this:

new Some::Class;    # bad! (but why?)

Some::Class->new(); # good!

Sadly

4条回答
  •  没有蜡笔的小新
    2020-11-29 08:42

    The indirect object syntax is frowned upon, for good reasons, but that's got nothing to do with constructors. You're almost never going to have a new() function in the calling package. Rather, you should use Package->new() for two other (better?) reasons:

    1. As you said, all other class methods take the form Package->method(), so consistency is a Good Thing

    2. If you're supplying arguments to the constructor, or you're taking the result of the constructor and immediately calling methods on it (if e.g. you don't care about keeping the object around), it's simpler to say e.g.

    $foo = Foo->new(type => 'bar', style => 'baz');
    Bar->new->do_stuff;
    

    than

    $foo = new Foo(type => 'bar', style => 'baz');
    (new Bar)->do_stuff;
    

提交回复
热议问题