in reply to A class that cannot be subclassed.

At $work, someone suggested that, if you have a class that you want not to be subclassed
... you're insane.

At least, at my work, that would be the first reaction.

Why be hostile to subclassing?

Replies are listed 'Best First'.
Re^2: A class that cannot be subclassed.
by kyle (Abbot) on Feb 28, 2008 at 04:30 UTC

    Our coding standards say to prefer composition over subclassing. There's a brief summary of some of the arguments at Consider composition instead of subclassing. I don't see that as a reason to be hostile to the practice to the point of taking steps to prevent it, but this might not have been a general situation either. I suppose there could be a class that the author knows would break if subclassed. In that case, it might make sense to try to force that not to happen.

      The original node made me think of "I need a class that can't be used on Tuesdays. I could just check localtime in new(), but somebody could intentionally set their computer's clock wrong..."

      I suppose there could be a class that the author knows would break if subclassed.

      If that were the case, then I would put the checking at/around the point that I thought would break if it was subclassed. I wouldn't go the indirect route and try to prevent all forms of subclassing. And this would also avoid the obvious and wise questioning of "why do you want to make subclassing fatal?". I would also question a conclusion so broad as "this will break if subclassed". I expect such would more correctly be stated as "this will likely break if subclassed in the obvious way".

      But that is based on a lot of speculation. It would be nice to know why such a bizarre (IMHO) requirement was formulated.

      - tye        

      Our coding standards say to prefer composition over subclassing.

      You have coding standards, so do you have code reviews or some sort of collective code ownership?

      "Our coding standards say to prefer composition over subclassing."

      That's fine. But do it with documentation, not code.