Being Explicit

A discussion with a friend who works mainly with Java has come to the old case of virtual-by-default vs. final-by-default.

When I come to declare a method, I can decide whether I want derived classes to be able to override it. Java does this by default, which kind of sucks because it opens up a way for people to override code you haven’t intended on letting them override, just because you forgot to mark the method as final. C# makes all methods final by default, which kind of sucks, since you can forget to make a method virtual and thus limit the deriving class from doing things it could have done if you had marked the method as virtual.

So why not take a third road? Why not just be constantly explicit about what you want to do? I think all methods declared in C# should be required to have a ‘sealed’ or ‘virtual’ (or ‘override’) modifier on them. This way, you would never be able to get away with not making the decision whether derived classes can override a method or not.

But that’s just a thought… :)

Advertisements

3 thoughts on “Being Explicit

  1. This is an interesting issue, with different pros and cons.

    I have 2 comments:

    1. There is also the performance issue: virtual methods cause a (small) performance hit as methods invocation goes through the VTable. So basically Java language makes a small performance sacrifice for the God of pure OO, whereas C# sacrifices pure OO for performance. Personnaly I favour C# approach.

    2. Your 3rd road states 3 options for method attribute: sealed, virtual and override.
    It’s also perfectly possible that a method simply hides an inherited member (using the new keyword in c#).

  2. There are 2 rules about optimization:
    1. Don’t do it.
    2. If you have to, don’t do it now.

    We should not care about the theoretical, minute performance benefits from any way of doing anything. We should care about doing things easy, correct and flexible. When things slows down, it’s more often than not caused by something other than an extra lookup in a vtable.

    When a vtable lookup really matters, then C# is the wrong choice. I would go further and say .NET is the wrong platform.

    The C# defaults are good for versioning, which is good if you do as Microsoft: Writing libraries and frameworks. It’s not good for us who writes applications. We have no clients to break, so the extra bureaucracy does not give us any good.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s