Strategies to extend an existing interface in .NET
August 24, 2016 Leave a comment
Let’s say you have the following interface in production code:
public interface IPrintable { void PrintMe(); }
…and you’d like to extend it in some way: add one or more parameters to the PrintMe method or add another method to the interface.
This will be difficult as it breaks all existing implementations of the IPrintable interface. If you own the whole code base then you may take the time and update all places where the interface is used.
If, however, this is not the case then you’ll need to follow another strategy.
One option is to create another interface and let it derive from the existing one:
public interface IPrintableExtended : IPrintable { void PrintMeExtended(string argument); void PrintMe(int howManyTimes); }
You can then start programming to the extended interface in all future code.
Another, more long term option is using the obsolete keyword in .NET and thereby discourage the usage of IPrintable. You can replace the existing interface with a brand new one and start programming to that instead. Note that this process can take years for all clients to update their code to the new interface instead.
One last option I can think of can be used for brand new interfaces so that they’ll be more forward-looking. Instead of a set of primitive arguments to a method you can let an object hold the parameters like here:
public class PrintArguments { public int HowManyTimes { get; set; } public string Format { get; set; } public bool Pretty { get; set; } } public interface IPrintable { void PrintMe(PrintArguments printArgs); }
You can then add new properties to the PrintArguments object if you need new arguments to the PrintMe method. You’ll probably need to adjust your code for default and missing values but existing code won’t break at least.
View all various C# language feature related posts here.