Joe
Joe

Reputation: 744

Optional methods in an interface

I need to change an interface that is used by more than one app. The change is only needed for this one app I am working on. I need to add a few more parameters to the method.

I do have access to change the code in the other apps and it would only take a few minutes to change the other apps to use the correct method signature. I could then make those apps do nothing with those extra parameters.

Or I could create an overload and have the other apps implement the methods and do nothing I guess. Or have them call to the original method without the extra parameters.

What's the best practice here, friends?

Upvotes: 2

Views: 269

Answers (3)

TcKs
TcKs

Reputation: 26632

You can add new interface (i.e. INewInterface) implementing the old one (i.e. IOldInterface). Ane then implement the INewInterface to the class/struct.

public interface IOldInterface {
    object DoSomething( int number );
}
...
public interface INewInterface : IOldInterface {
    object DoSomething( int number, TimeSpan time );
}
...
public class MyClass : IOldInterface, INewInterface {
    public object DoSomething( int number ) { ... }
    public object DoSomething( int number, TimeSpan time ) { ... }
}

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500175

I would try to avoid creating methods which don't really "fit" with all reasonable implementations. A couple of options:

  • Consider encapsulating the parameters in a separate type; that tends to make them more flexible
  • Consider extending the existing interface with a new interface, and implement that just in the app that needs it.

It's not entirely clear what's implementing the interface or what's using it I'm afraid, so it's slightly hard to give very concrete advice.

Upvotes: 3

Andy Thomas
Andy Thomas

Reputation: 86391

If you control all the code, it may be reasonable and simplests just to modify the interface.

However, this change may introduce additional costs beyond just the initial coding time.

Sometimes an alternative is to introduce a new interface that extends the first, that's used only by new code, to avoid introducing additional costs and risks elsewhere.

Upvotes: 1

Related Questions