Saturday, May 29, 2004

To be or not to be virtual

It's interesting to see how languages look at a specific design decision in different ways. I'm of course talking about the Java, C# and C++. In particular, the case of virtualness.

Java, by default, makes every method of a class virtual by default. You need to explicitly specify if you DON'T want to make it overridable by using the keyword "final". C# goes the C++ way in making every method non-virtual by default.

Why did the designers choose to do it differently? From Java's perspective, I assume they were thinking about extensibility. So if the class doesn't do what you want exactly, you can always derive and add your own functionality. This affords you with some leeway in the design. If you feel like something is not right after the initial phase, you can always go back and make changes. On the other hand, you get good performance with C# and C++ cause the function calls are static - no indirection.

What do you think? Which dyou prefer? I guess this is a grey area like pretty much everything in software design. There are always tradeoffs. I guess there is no "right" answer here.

I personally feel that C#/C++ is the better option. Not only for the performance reasons, but also because the class designer is in complete control. You decide how much extensibility you want your class to have. You can make sure that your class will not be used for something it was not meant to be. Yeah, you can do the same in Java too, but it takes more code, even if it is only one extra keyword. Most functions in classes will NOT have the "final" keyword on them. C#/C++ might even make you think about design harder since it's sort of set in stone once you release. With Java there might be a tendency to think like "oh, we can always derive and change later if something's not right".

No comments: