Alex Rivera | Logout

Adding new functions to an interface

Asked 2010-07-15T13:42:37.017
11

I need to create overloads for functions on an existing interface without affecting any components that currently implement or make use of the interface (ideally).

I figure I have a couple of options:

Simplified Original interface:

public interface IServerComponent
{
    bool Add(int a, int b);
}

I can add the new overloaded functions to the interface and force every class that implements the interface to implement the new functions.

public interface IServerComponent
{
    bool Add(int a, int b);
    bool Add(int a, int b, int c);
}

Or I can create a new interface that implements the original interface. Then other classes that make use of the original won't need to change and any new classes can implement the new interface...

public interface IServerComponent2 : IServerComponent
{
    bool Add(int a, int b, int c);
}

What is the best practice is this situation? Are there any other options available?

Thanks

Edit
Report

1 Answer

1

I realize your example is contrived but I want to give you a contrived answer that is different from what you are expressing so that maybe you can think about it in a different way. Instead of having your interface method operate on something concrete it might make sense to it instead work on something abstract.

For example

public interface IAddableThings
{
  int a;
  int b;
}

public interface IOtherAddableThings : IAddableThings
{
  int a;
  int b;
}

public interface IServerComponent
{
    bool Add(IAddableThings things);
}

If this really is an Add then I think this makes a lot more sense, but if it is really more like Calculate(), you would then want to move some or all of that methods operation down to the IAddableThings objects.

public interface IAddableThings
{
  int a;
  int b;
  bool CalculateMe();
}
answered 2010-07-15T14:03:46.223

Your Answer