开发者

C# - simplifying interface

Is it possible to somehow simplify an interface? The goal is to provide a noise-reduced API for the user thats going to use it.

An example could be that the inter开发者_如何学编程face IFoo has 25 methods defined and I only want to expose 5 of them to the user, how would I do that in a clever and elegant way?


You can't. An interface is by definition public on all the methods. That's why it is called a contract.

Try splitting it into a number of interfaces:

  IBaseFoo (5 methods)
  IFoo : IBaseFoo  (20 more methods)

This is how it is commonly practiced. However, you cannot prevent the user form knowing your 20 other methods, unless you make IFoo a private interface.

Then you write a wrapper class which just exposes IBaseFoo to the user. IFoo can be cast directly into an IBaseFoo to be returned to the user.


You create an interface that only contains those five methods and derive IFoo from it.


Create a reduced version of the interface that only specifies the methods you want your users to have access to, have your bigger interface inherit from it, and only expose the base interface to your users.

Or create a wrapper class with fewer methods for it and only expose that to your users.


Some interfaces can be simplified with moving some methods to extension methods. Works for particular type of interfaces - as mentioned earlier - no genral way to make any interface smaller.

Interface with multiple methods that are expected to be implemented in very particular way like:

interface IMy 
{
    int GetFoo(string name); // calls GetFoo(name, DefautlFoo, DefaultBar)
    int GetFoo(string name, string foo); // calls GetFoo(name, foo, DefaultBar)
    int GetFoo(string name, string foo, string bar);
}

Can be converted to interface with one method and 2 extension methods:

interface IMy 
{
  int GetFoo(string name, string foo, string bar);
}

static class MyExtensions
{
    int GetFoo(this IMy my, string name)
    {
       return my.GetFoo(name, DefaultFoo, DefaultBar);
    }
}

There could be some less trivial cases of interface members that can be moved out of interface to extension methods. I.e. see http://msdn.microsoft.com/en-us/vcsharp/bb625996.aspx for example of extending interface with extra functionality without changin interface or look at LINQ extension methods for IEnumerable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜