kyle has asked for the wisdom of the Perl Monks concerning the following question:
At $work, someone suggested that, if you have a class that you want not to be subclassed, ever, bless into the package directly like so:
sub new { bless {}, __PACKAGE__ }
I said that this will fail silently for the subclass, and I'd rather have an obvious explosion:
sub new { my $class = shift; if ( $class ne __PACKAGE__ ) { die "Class $class attempts to inherit from final class, ' . __P +ACKAGE__; } # ... }
Now that I look at it, though, a subclass need only override new, and it's home free either way. So I'm wondering, is there a way to make a class that some other module cannot use as a base class?
I figure it's enough just to die with an obvious and clear message about what was intended. If another programmer wants to violate that, then it's understood that the warranty is void. As acceptable as that is, it would be even better if the failure could happen at compile time (i.e., when one tries to use the subclass) so we don't even have to wait for the first instantiation to cause an explosion.
Update: Just to be clear (because I realize now that I have not been), I do not advocate this practice. I'm not asking for a better way to do this because I think it's a good idea to do it. I'm asking out of curiosity because I couldn't think of a good way to do it, and I thought it was an interesting problem. I suspect that doing this to a class rarely, if ever, serves a good purpose.
|
|---|