Top interface Questions

List of Tags
396
Mike Stone

Ok, I may resort to a tad ranting here, so let me apologize in advance, but I'm really curious if others find this pattern annoying too (and I wonder if it is a justifiable pattern)…

So, after just looking at a particular question, I noticed that almost all of the responses suggested creating an interface for injecting a mock in some test code.

I don't mind using interfaces, and sometimes they can really help in static typed languages like C# and Java… but I do mind seeing interfaces for almost every class in a system(or in general being used where they aren't really needed).

I have 2 major problems with using an interface when it isn't called for:

  • You abstract away where the implementation is coming from. This problem has a couple consequences… in an IDE, it means that when I try to browse to the source of this method being called… I get taken to an interface instead of some code that I can look at and see what is going on. This bothers me a lot, but also this is a real problem to me to hide where the implementation is coming from (sometimes it can be in non-obvious locations).
  • It adds ANOTHER file to the system. I tend to be a minimalist in my programming… if I don't really need another method, or another class, or even another file… not unless that extra thing is justified (flexibility that is going to be used, or makes the design cleaner, or provides some real benefit).

Now… if you are testing something, and you create an interface JUST TO ALLOW MOCKING… this seems to be adding a layer of minor headaches for no real benefit. What does creating the interface do that just overriding the class won't do? What is so bad about having a mock that merely overrides some methods of the single implementation class?

I guess it should be no surprise then that I much prefer Java's default virtual methods (ie requiring a final keyword to have a method that CAN'T be overriden) to C#'s default final methods… and I also tend to avoid the final keyword on methods and classes too.

So is there something to using interfaces that I am missing? Is there some hidden benefit of using an interface when you have 1 version of a class and no immediate need to create an interface?

Answered By: Hallgrim ( 160)

A big headache with interfaces in Java and C# is that they give you so few options to evolve your contract. E.g.:

interface ILogSink {
  Log(DateTime timestamp, string message);
}

If you define this in a framework and have a lot of different external consumers that all implement this interface you cannot change it without breaking their implementation. If you need to change it in the next version, you end up with something like:

interface ILogSinkVersion2 {
  Log(DateTime timestamp, string message, CultureInfo culture);
}

If you use a base class on the other hand, you can start out with:

class LogSink {
  void Log(DateTime timestamp, string message);
}

And evolve it to:

class LogSink {
  [Obsolete("Please include CultureInfo using Log(DateTime, string, CultureInfo)")]
  virtual void Log(DateTime timestamp, string message) {
  }

  virtual void Log(DateTime timestamp, string message, CultureInfo culture) {
    // Call old method for old implementations:
    Log(timestamp, message);
  }
}

This way you can evolve your code without forcing every implementation of the contract to consume your changes immediately.

Update: This is not a big deal if you sit on your own island and own all your code. However if you maintain a framework interface like log4net's ILog interface or .NET frameworks IDisposable interface, you need a quite good reason to add or change methods, since it will affect a few thousand implementations throughout the world.

How do I setup a class that represents an interface? Is this just an abstract base class?

Answered By: Mark Ransom ( 249)

To expand on the answer by bradtgmurray, you may want to make one exception to the pure virtual method list of your interface by adding a virtual destructor. This allows you to pass pointer ownership to another party without exposing the concrete derived class. The destructor doesn't have to do anything, because the interface doesn't have any concrete members. It might seem contradictory to define a function as both virtual and inline, but trust me - it isn't.

class IDemo
{
    public:
        virtual ~IDemo() {}
        virtual void OverrideMe() = 0;
};

class Parent
{
    public:
        virtual ~Parent();
};

class Child : public Parent, public IDemo
{
    public:
        virtual void OverrideMe()
        {
            //do stuff
        }
};

You don't have to include a body for the virtual destructor - it turns out some compilers have trouble optimizing an empty destructor and you're better off using the default. http://connect.microsoft.com/VisualStudio/feedback/details/560640/empty-c-destructors-prevent-optimization

189
Seb Nilsson

What are the differences in implementing interfaces implicitly and explicitly in C#?

When should you use implicit and when should you use explicit?

Are there any pros and/or cons to one or the other?

Answered By: mattlant ( 143)

Implicit is when you define your interface via a member on your class. Explicit is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: IList.CopyTo would be implicitly implememnted as:

public void CopyTo(Array array, int index)
{
    throw new NotImplementedException();
}

and explicity as:

void ICollection.CopyTo(Array array, int index)
{
    throw new NotImplementedException();
}

The difference being that implicitly is accessible throuh your class you created when it is cast as that class as well as when its cast as the interface. Explicit implentation allows it to only be accessible when cast as the interface itself.

myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.

I use explicit primarily to keep the implementation clean, or when i need two implemetations. But regardless i rarely use it.

I am sure there are more reasons to use it/not use it that others will post

EIT: See the next post in this thread for excellent reasoning behind each.

151
Boris Callens

It's weird that this is the first time I've bumped into this problem, but:

How do you define a constructor in a C# interface?

Edit
Some people wanted an example (it's a free time project, so yes, it's a game)

IDrawable
+Update
+Draw

To be able to Update (check for edge of screen etc) and draw itself it will always need a GraphicsDeviceManager. So I want to make sure the object has a reference to it. This would belong in the constructor.

Now that I wrote this down I think what I'm implementing here is IObservable and the GraphicsDeviceManager should take the IDrawable... It seems either I don't get the XNA framework, or the framework is not thought out very well.

Edit
There seems to be some confusion about my definition of constructor in the context of an interface. An interface can indeed not be instantiated so doesn't need a constructor. What I wanted to define was a signature to a constructor. Exactly like an interface can define a signature of a certain method, the interface could define the signature of a constructor.

Answered By: Jon Skeet ( 116)

You can't. It's occasionally a pain, but you wouldn't be able to call it using normal techniques anyway.

In a blog post I've suggested static interfaces which would only be usable in generic type constraints - but could be really handy, IMO.

One point about if you could define a constructor within an interface, you'd have trouble deriving classes:

public class Foo : IParameterlessConstructor
{
    public Foo() // As per the interface
    {
    }
}

public class Bar : Foo
{
    // Yikes! We now don't have a parameterless constructor...
    public Bar(int x)
    {
    }
}

I have had recently two telephone interviews where I've been asked about the differences between an Interface and an Abstract class. I have explained every aspect of them I could think of, but it seems they are waiting for me to mention something specific, and I don't know what it is.

From my experience I think the following is true. If I am missing a major point please let me know.

Interface:

Every single Method declared in an Interface will have to be implemented in the subclass. Only Events, Delegates, Properties (C#) and Methods can exist in a Interface. A class can implement multiple Interfaces.

Abstract Class:

Only Abstract methods have to be implemented by the subclass. An Abstract class can have normal methods with implementations. Abstract class can also have class variables beside Events, Delegates, Properties and Methods. A class can only implement one abstract class only due non-existence of Multi-inheritance in C#.

  1. After all that, the interviewer came up with the question "What if you had an Abstract class with only abstract methods? How would that be different from an interface?" I didn't know the answer but I think it's the inheritance as mentioned above right?

  2. An another interviewer asked me what if you had a Public variable inside the interface, how would that be different than in Abstract Class? I insisted you can't have a public variable inside an interface. I didn't know what he wanted to hear but he wasn't satisfied either.

See Also:

Answered By: Michael Burr ( 87)

While your question indicates it's for "general OO", it really seems to be focusing on .NET use of these terms.

In .NET (similar for Java):

  • interfaces can have no state or implementation
  • a class that implements an interface must provide an implementation of all the methods of that interface
  • abstract classes may contain state (data members) and/or implementation (methods)
  • abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itslef)
  • interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).

As general OO terms, the differences are not necessarily well-defined. For example, there are C++ programmers who may hold similar rigid definitions (interfaces are a strict subset of abstract classes that cannot contain implementation), while some may say that an abstract class with some default implementations is still an interface or that a non-abstract class can still define an interface.

Indeed, there is a C++ idiom called the Non-Virtual Interface (NVI) where the public methods are non-virtual methods that 'thunk' to private virtual methods: