MarcoS
MarcoS

Reputation: 17711

Can I create an instance of a class inside a method of the same class in Perl?

Is it reasonable to create an instance of a class inside a method of the same class?

I ask about "reasonability" and not "feasibility" because I could write a working example, like this:

package MyPkg;

sub new {
    ...
}

sub myMethod {
    my ($class, $param) = @_;
    my $obj = $class->new();
    ...
}

and the usage is:

use MyPkg;
my $result = MyPkg->myMethod("abc");

This architecture does work as expected (in $result I have the result of the call of myMethod on a "transient" object), and the caller is not even forced to explicitly instantiate a new object and then use it to call its methods.

Though, I feel this is not "Perl-ish", I mean... I don't like it. I feel something is flawed with this approach, but can't identify the exact reason.

Is there a more 'standard' solution?

Upvotes: 0

Views: 116

Answers (2)

Miller
Miller

Reputation: 35198

Nothing requires a constructor to have the name new, that's just convention. Your myMethod sub may have a different name, but it's also a constructor.

One example of this is XML::LibXML. It has a standard constructor, but also two other constructors with specific purposes:

use XML::LibXML '1.70';

# Parser constructor

$parser = XML::LibXML->new();
$parser = XML::LibXML->new(option=>value, ...);
$parser = XML::LibXML->new({option=>value, ...});

# Parsing XML

$dom = XML::LibXML->load_xml(
    location => $file_or_url
    # parser options ...
  );

# Parsing HTML

$dom = XML::LibXML->load_html(...);

The second two are probably wrappers for new, but they're also constructors.

Additionally, some objects are designed to be immutable. If they allow operations to still be performed on them, they will need to return a new object of the same type.

All this is to say, yes, what you've doing is fine.

Upvotes: 2

tobyink
tobyink

Reputation: 13664

Yes, you can do this. It's quite widely done.

Upvotes: 2

Related Questions