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.


In reply to A class that cannot be subclassed. by kyle

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.