http://www.perlmonks.org?node_id=1069412


in reply to Class confusion when testing using ref()

Those subclasses seem pointless, as they aren't introducing any new behaviour. The StationaryParticle in particular seems behaviourally identical to its parent class, and the MoveableParticle class doesn't have any behaviour related to movement :(

(In the absence of such behaviour) Perhaps what you wanted instead are so called factory methods e.g.
package Particle; ... sub newMoveableParticle { my $class = shift; my $p = $class->new( @_ ); $p->set( 'is_moveable', 1 ); return $p; } sub newStationaryParticle { my $class = shift; my $p = $class->new( @_ ); $p->set( 'is_moveable', 0 ); return $p; }

UpdateThe following is incorrect as kindly pointed out by tobyink

$REGISTRY{$self} = $self;
In a long running program, this could cause a memory leak unless you are cleaning up the registry in some way. This could be automated by letting objects 'de-register' themselves when they go out of scope e.g.
DESTROY { my $self = shift; delete $REGISTRY{$self}; }
End of update

What do these objects do anyway? The API seems not very intuitive to me.

Replies are listed 'Best First'.
Re^2: Class confusion when testing using ref() (isa crock)
by tye (Sage) on Jan 05, 2014 at 23:35 UTC

    People teaching OO feel the need to teach inheritance and they tend to make a big deal of it. This leaves most students of OO with the very unfortunate habit of starting any design project with one of the foremost questions in their mind being "which classes should inherit from which other classes?". So it isn't surprising that I often see uses of inheritance that seem very stretched.

    OO design is done much, much better when inheritance is a last resort (or just avoided entirely). [In languages with interfaces, inheritance is sometimes used to apply interfaces, but it is an implementation detail that inheritance is used for that and it is not really a use of real inheritance and not something that one needs to avoid when using such languages.]

    - tye        

Re^2: Class confusion when testing using ref()
by tobyink (Canon) on Jan 07, 2014 at 19:33 UTC

    This could be automated by letting objects 'de-register' themselves when they go out of scope e.g.

    DESTROY { my $self = shift; delete $REGISTRY{$self}; }

    The above will not actually work. DESTROY will never be called because $REGISTRY{$self} will have bumped the reference count. (Or rather it will get called, but only when the entire process ends - not when the object goes out of scope.)

    Instead, you should use Scalar::Util to weaken $REGISTRY{$self} as part of the object construction. No DESTROY sub is necessary for this to work.

    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name