Perl - Calling subclass constructor from superclass (OO)

Posted by Emmel on Stack Overflow See other posts from Stack Overflow or by Emmel
Published on 2010-05-05T19:39:45Z Indexed on 2010/05/05 20:08 UTC
Read the original article Hit count: 231

Filed under:
|
|
|
|

This may turn out to be an embarrassingly stupid question, but better than potentially creating embarrassingly stupid code. :-) This is an OO design question, really.

Let's say I have an object class 'Foos' that represents a set of dynamic configuration elements, which are obtained by querying a command on disk, 'mycrazyfoos -getconfig'. Let's say that there are two categories of behavior that I want 'Foos' objects to have:

  • Existing ones: one is, query ones that exist in the command output I just mentioned (/usr/bin/mycrazyfoos -getconfig`. Make modifications to existing ones via shelling out commands.

  • Create new ones that don't exist; new 'crazyfoos', using a complex set of /usr/bin/mycrazyfoos commands and parameters. Here I'm not really just querying, but actually running a bunch of system() commands. Affecting changes.

Here's my class structure:

Foos.pm

package Foos, which has a new($hashref->{name => 'myfooname',) constructor that takes a 'crazyfoo NAME' and then queries the existence of that NAME to see if it already exists (by shelling out and running the mycrazyfoos command above). If that crazyfoo already exists, return a Foos::Existing object. Any changes to this object requires shelling out, running commands and getting confirmation that everything ran okay.

If this is the way to go, then the new() constructor needs to have a test to see which subclass constructor to use (if that even makes sense in this context). Here are the subclasses:

Foos/Existing.pm

As mentioned above, this is for when a Foos object already exists.

Foos/Pending.pm

This is an object that will be created if, in the above, the 'crazyfoo NAME' doesn't actually exist. In this case, the new() constructor above will be checked for additional parameters, and it will go ahead and, when called using ->create() shell out using system() and create a new object... possibly returning an 'Existing' one...

OR

As I type this out, I am realizing it is perhaps it's better to have a single:

(an alternative arrangement)

Foos class, that has a

->new() that takes just a name

->create() that takes additional creation parameters

->delete(), ->change() and other params that affect ones that exist; that will have to just be checked dynamically.

So here we are, two main directions to go with this. I'm curious which would be the more intelligent way to go.

© Stack Overflow or respective owner

Related posts about perl

Related posts about oop