07 Jan 2009

In general, I prefer C# over Java. It's a matter of personal taste, but I find C# more elegant, even if they are very close to each others. But there is something about C# that always bugs me: the way inheritance is declared.

If we look at this code:

public class FooBar : Bar, Foo
{
}

Apart from Visual Studio's tooltip that helps you, how do you know if Bar is a interface or a class? It can be both, and there is no way of telling.

We obliviously know that Foo is an interface, as only one base class can be defined and it has to be right after the ":" character (see the Class base specification of the C# language).

A class declaration may include a class-base specification, which defines the direct base class of the class and the interfaces implemented by the class.

class-base:
:   class-type

:   interface-type-list

:   class-type   ,   interface-type-list

interface-type-list:
interface-type

interface-type-list   ,   interface-type

But what about Bar? According to the language specification, it can be either an class or an interface, we cannot know just by looking at it. Guidelines for Names that states that interfaces should be prefixed with I, so we could assume that it is a class. However, in this particular example, Foo is an interface for sure but is not prefixed with I, so we cannot assume that Bar is an interface, right?

Now, if we look at Java's syntax, it is much neater:

public class FooBar extends Bar implements Foo
{
}

Looking at this, there is no doubt that Bar is a class and Foo is an interface (see Java Language Specification parts on Superclasses and Superinterfaces). Even if the developer gave crappy names, we can sort out what is an interface and what is a class.

Now, that said, Visual Studio will always tell you if it is a class or an interface. but if you open the source file with something else than a smart IDE? Notepad for example? I think that the language should speak for itself and not rely on naming conventions. With C#, you can have a doubt, while with Java there is none.

But I still love C# for everything else, I think...



blog comments powered by Disqus