Virtually everything

time to read 3 min | 418 words

This is a short reply to Ward Bell’s post, Do Not Make Every Method Virtual. More specifically, I have an issue with this statement:

My argument is with opening up the class blindly and totally by making everything virtual. Suddenly nothing in the class is truly “closed for modification.” The “virtual” keyword announces to the world “here is my extension point.” When every method is virtual, the world is invited to change every method.

I think that there is some confusion here. The original class is closed for modification. I can’t change it. I can create a new class extending the behavior. That is what OCP is all about.

Ward is giving the example of an Elevator, and overriding its Up() method:

I knew that Up() sent the elevator ascending. But I can’t stop someone from re-implementing Up() so that it descends instead. Maybe base.Up() triggers the doors to close. The developer might call base.Up() too late, sending the elevator in motion before the doors have closed. The developer could replace my base.Up with something that juggled the sequence of door closing and elevator motion methods, interleaving custom behaviors, yielding upward motion that failed to satisfy some other elevator guarantees.

And the problem here is… ?

I am sorry, but I see some descriptions of potential bugs (or desired behaviors) listed here. I fail to see a problem.

But I write frameworks for you to use. You’ve licensed my product and you’re paying me for support. When the elevator goes down instead of up; when the doors close suddenly and injure a rider; when the elevator simply stops … you don’t say “I wonder what I did?” You say “that elevator we bought is a piece of crap.”

Well, guess what, if you switch the wires in the elevator, it will behave strangely. Nothing out of the ordinary here. And by switching the wires you accept responsibility for the actions you did.

I have several frameworks available that are nothing but huge extension points that the user can plug into at any point and at any time. More than that, I have those extension points at several layers, so they can choose at what level to interact. And no, those aren’t designed extension points, they fall out of the way I build software. And so far, based on actual evidence on the field, it is working.