Why Are So Many Of The Framework Classes Sealed?

Why Are So Many Of The Framework Classes Sealed?

Rate This
  • Comments 27

I talked earlier this month about some issues in subclassing, and recommended sealing your classes. A Joel On Software reader asks why Microsoft ships so many sealed classes in the framework.  The poster said: "I've yet to see a reasonable explanation about why they limited flexibility in such a way. "

Well, every public class that my team produces is sealed if possible.  If it is not possible to seal a class then, if possible, it has an inheritance demand on it so that only someone with the MSFT private key can subclass it.  My reasons for insisting upon this policy boil down to one overriding principle:

Good code does exactly what it was designed to do, no more, no less.

Let me expand upon that in four ways.

1) Philosophical.  OOP design includes subclassing to represent the polymorphic "is a" relationship between two things.  A Giraffe IS AN Ungulate IS A Mammal IS AN Animal...  Unless I can think of a clear case where a customer would need to express an IS A relationship with some code that I produce, I don't allow for such cases.

2) Practical.  Designing classes so that they can be effectively extended by third parties is HARD.  (Look at the collection base classes for example.) You have to get the design right -- what is protected?  You have to implement that design correctly. The test matrix grows enormously because you have to think about what weird things people are going to do. You have to document the protected methods and write documentation on how to properly subclass the thing. 

This is all expensive and time consuming -- that is time that we could be spending looking for bugs in more important user scenarios, planning future versions, fixing security holes, whatever.  There is only a finite amount of developer time we can spend on designing and implementing code, so we have to spend it the way that benefits customers most.  If the class is not designed to be extended, I'm going to avoid all that expense by sealing it.  I am not going to release half-baked classes that look extensible but in fact are not quite there.

3) Compatible.  If in the future I discover that I should have sealed a class, I'm stuck.  Sealing a class is a breaking change.  If I discover that I should have left a class unsealed, unsealing in a future version is a non-breaking change.  Sealing classes helps maintain compatibility.

4) Secure. the whole point of polymorphism is that you can pass around objects that look like Animals but are in fact Giraffes.  There are potential security issues here.

Every time you implement a method which takes an instance of an unsealed type, you MUST write that method to be robust in the face of potentially hostile instances of that type.  You cannot rely upon any invariants which you know to be true of YOUR implementations, because some hostile web page might subclass your implementation, override the virtual methods to do stuff that messes up your logic, and passes it in.  Every time I seal a class, I can write methods that use that class with the confidence that I know what that class does.

Now, I recognize that developers are highly practical people who just want to get stuff done.  Being able to extend any class is convenient, sure.  Typical developers say "IS-A-SHMIZ-A, I just want to slap a Confusticator into the Froboznicator class".  That developer could write up a hash table to map one to the other, but then you have to worry about when to remove the items, etc, etc, etc -- it's not rocket science, but it is work.

Obviously there is a tradeoff here.  The tradeoff is between letting developers save a little time by allowing them to treat any old object as a property bag on the one hand, and developing a well-designed, OOPtacular, fully-featured, robust, secure, predictable, testable framework in a reasonable amount of time -- and I'm going to lean heavily towards the latter.  Because you know what?  Those same developers are going to complain bitterly if the framework we give them slows them down because it is half-baked, brittle, insecure, and not fully tested!   

  • Well said. Thank you for the explanation. I'll remember it the next time I hear someone whining and moaning about this. :-)
  • Ingo Rammer has an article on why many of the Windows Forms classes are sealed:

  • Handy info! I do hope nobody wants to extend the Giraffe class. Override on the NumberOfLegs property or something? <g>
  • Not to whine and moan -- I agree with much of what Ingo Rammer wrote in the link above, and much of this article -- but...

    This is excellent information and an excellent philosophy for most development teams.

    However, when we're talking the BASE class library different factors come into play. And as much as Windows Forms and ASP.NET are extensions to that, they are vital extensions that help me do my job (thanks guys!)

    Yes, designing classes so that they can be extended is hard, but that's why we don't all write the BCL/FCL. In fact that's the whole point of it. .Net is such a productive environment because of all the hard work that I don't have to do -- you did it. That's why I pay you $2500/year+, and consider it cheap.

    Yes, there is finite time. But making a class and the functionality it encapsulates easily extendable is just as much a feature as making menus have gradient backgrounds, and I'll argue to which one is more important.

    If you ever say "No developer will ever want to replace this feature with something else", you're wrong. I'm sure of it. It may only be one, and yes, you have to weigh that -- but that one developer definately will whine at you. It may be me.

    Also on the last point about security -- if you can write methods that take sealed classes without worrying about "hostile instances" (I like that phrase), then isn't unsealing a class a breaking change? If I write code that assumes ImageList is sealed, then you unseal it, you've introduced potential security holes in my code.
  • Re: gradiant menus: You're preaching to the choir here!

    Re: base class libraries: yes, there certainly are portions of the library which are there solely because they need to be extended. But there is a big difference between "must be extended, by design" and "might be extended, maybe, someday, by someone, perhaps." To put the work involved in the former to achieve the latter is not the best way to spend limited effort.

    Re: "no developer" -- sure, its likely that given any task, someone will want to do it at some point -- but you remember what Aesop said about pleasing all of the people all of the time? You're not paying us to be all things to all people, you're paying us to come up with the best balance of features for the platform as a whole.

    Re: breaking change -- sorry, I was not clear. ANY change ANYWHERE in the code can cause SEMANTIC breaking changes. After all, changing the code changes its behaviour!

    By "breaking change" I almost always mean "a change that will make code that used to compile now not compile". That is, I'm talking about SYNTACTIC breaking changes.
  • Not just fail to _compile_, but fail to verify as well (assuming you don't have SkipVerification). And in case anyone cares: http://weblogs.asp.net/ptorr/archive/2004/01/15/58902.aspx

    I was also thinking of writing a short (ha!) blog on language-compiler-enforced rules versus runtime-enforced rules, but it's kind of obscure.

  • True on all counts (except I'd rather instead of pleasing everyone you pleased me, but I'll pitch that idea to Mr. Gates next time he calls me to see how I like Microsoft. )

    I'm not arguing to harass you here, as I can understand all of the reasons you posted (although #2 gets the lions share of the credit in my mind) -- I just want to make sure to keep you guys on your toes.

    I guess the thing that made me want to raise my voice was the line "If the class is not designed to be extended, I'm going to avoid all that expense by sealing it". I just want to make sure that the extensibility scenario is made (or stays) a first-class concern during the design. It's a very important feature to me, and many others like me (Insane German-Scottish-Americans who own a hermit crab -- we're an important demographic!)

    And Mr. Torr -- please do write that if you have the urge. You can tell by the past popularity of Chris Brumme's blog that the community loves obscure technical information.

  • You make some good points about why classes should be sealed, private, protected, or whatever. And the Ingo Rammer article makes some further points about why classes which straddle the managed/unmanaged divide are sealed.

    It all makes perfect sense, ....., until that moment when you want to extend or override the class in some fashion.

    Take, for example, the CollectionEditor class. This is a class that contains a private nested form class.

    Firstly, its been designed such that the form class in inaccessible at runtime, and instead one has to go through all kinds of hoops to create a design time lookalike environment to get a colelction editor up at all. Secondly, its been designed with virtually no extensibility in mind at all. Something as simple as a valiadtion step (OnClosing) cannot be achieved with the class as it stands.

    The choices are stark - reimplement the class from scratch, or seek refuge in unsavoury practices using reflection.

    I agree that everything should be sealed, private, whatever unless its been designed for extension and reuse, but I also suggest that everything in the BCL should be designed for extension/reuse unless theres a damn good reason not to.
  • > everything in the BCL should be
    > designed for extension/reuse
    > unless theres a damn good reason
    > not to

    We could do that. But that would then present us with a choice of three options. Which do you like best?

    1) cut some other features that some users want
    2) do a shoddy job
    3) ship years late

    Because of "fully featured", "well written" and "on time", you only get to pick TWO.
  • While I fully agree with the "time is money" argument, which is at the root of most of your assertions, I do think that there are some potential answers to the dilemma:

    1. Inheritance is not the only means for extending existing functionality. The GoF book for example discourages inheritance and provides lots of alternative design patterns for this purpose.

    Another example: STL collections are extensible in that you can roll-your-own collection and use it in the provided algorithms. Yet inheritance isn't used at all.

    2. Some features provided by some programming languages do make it easier to use inheritance in a safer way. Specifically DBC. See languages such as Eiffel and D.

    3. You could provide two implementation of various classes: one sealed and optimized, the second open and safe. Obviously this could double your development time, but it would satisfy many of the other constraints.

    The bottom line: through proper design, and using the appropriate tools, even complex systems can be made "fully featured", "well written" and "on time". It's not easy though, which is why almost nobody ever does.
  • It's certainly true that "time is money", but my argument is more general. What I'm getting at is more "available resources are finite, potential features are infinite, so choose wisely what you implement".

    Clearly this subject has touched a nerve. I'd like to cover it in more detail later, particularly the differences between sealing a class (preventing inheritance) and sealing a method (preventing overriding). There are ways to achieve many of my desired goals by good use of method sealing without preventing inheritance. But I've spent too much time on this subject already for this week.
Page 1 of 2 (27 items) 12