in reply to Calling subclass’ method from superclass

I want to make my own ‘parent’ subroutine, which would return an ‘Own::Dir’ object of a file's (or a directory's) parent directory. Because it should work the same for ‘Own::File’ and ‘Own::Dir’, I want to define it in ‘Own’, so that those two can inherit it. The problem is that the subroutine needs to invoke Own::Dir->new in order to make the ‘Own::Dir’ object it's supposed to return.

Since you are defining this subroutine to always return an object of type Own::Dir, I think it'd probably be fine to just call that constructor directly: return Own::Dir->new($parent) (no $ before Own).

One thing to think about would be whether you want to make Own easily subclassable, such that this method on a subclass of Own would return a subclass of Own::Dir. In that case, one way to do that might be to abstract the creation of the object out into another method on Own, so that this method could be easily overridden by a subclass.

Replies are listed 'Best First'.
Re^2: Calling subclass� method from superclass
by Fendo (Novice) on Feb 03, 2019 at 11:14 UTC
    Thank you; removing the sigil did the trick! However, I'm not sure if I understand your second paragraph, about subclassing, well. Are you saying I might want to move a part of the method into a different one, which could be utilised by similar methods to return objects of different classes (as opposed to only ‘Own::Dir’)?

      I think example code would go a long way here. If you think it's likely that someone might want to subclass Own and Own::Dir, then in the following, consider that in Own::parent, Own::Dir->new is hardcoded, and so, someone who wants to override Own::parent and call the superclass method, but wants to return their own subclass of Own::Dir, would have to find some workaround to do so. OTOH, if Own is some internal class, this case might be so unlikely that this may just be overthinking things.

      use warnings; use 5.012; package Own { sub parent { my $self = shift; say "called Own::parent()"; # Debug return Own::Dir->new('...'); } } package Own::File { use parent -norequire, 'Own'; use parent 'Path::Class::File'; } package Own::Dir { use parent -norequire, 'Own'; use parent 'Path::Class::Dir'; } say "Own::File->parent: ", Own::File->new('.')->parent; say "Own::Dir->parent: ", Own::Dir->new('.')->parent;