简体   繁体   English

针对接口编程:什么时候不将方法声明为接口方法?

[英]Programming against interfaces: When not to declare methods as interface methods?

I am beginning to program against interfaces and am trying to understand when it is unnecessary to declare a method on the interface. 我开始针对接口进行编程,并试图了解何时不需要在接口上声明方法。

My specific example is, I have some class 我的具体例子是,我有一些课

public class SomeClass : ISomeInterface
{

    public void SomeInterfaceMethod() 
    {
        if(doOtherStuff() == 1)
        {
            // do more stuff
        }

    }

    protected int doOtherStuff()
    {
        return 1;
    }
}

How do I know when doOtherStuff should or should not be declared on the interface? 我怎么知道什么时候应该在接口上声明doOtherStuff

My assumption is when the method isn't necessary for communication with other classes. 我的假设是该方法对于与其他类的通信而言不是必需的。 Its simply implementation detail to get the job done. 它只需简单的实现细节即可完成工作。

More specifically, I have a message bus. 更具体地说,我有一条消息总线。 I am trying to decide if the handler of a message should be an interface method. 我正在尝试确定消息的处理程序是否应该是接口方法。

Well, semantically what is a ISomeInterface ? 那么,语义什么 ISomeInterface What does it do ? 它是什么的?

For example, suppose you have an interface: 例如,假设您有一个接口:

public interface IDriveable
{
    void Drive();
}

You would reasonably expect anything which implements this interface to be something that you can drive. 您可以合理地期望实现该接口的任何东西都是您可以驱动的东西。 But that could be a lot of things. 但这可能是很多事情。

A Car can implement IDriveable . Car可以实现IDriveable It will also have other methods, such as methods to get in or out of the car or to fill it with gas. 它还将具有其他方法,例如上下车或向车内加气的方法。 Those don't make sense for something that's just "driveable*, they just make sense for a car. So they belong there. (Or perhaps on other interfaces which Car implements.) 那些没有的东西, 只是 “操控性*,只是它的意义一辆汽车是有意义的。因此,他们属于那里。(或者其他接口上的哪些Car工具。)

It's not a technical issue, it's a question about the natural semantics of the types that you're building. 这不是技术问题,而是关于您要构建的类型的自然语义的问题。 ISomeInterface doesn't really tell me much about what it should be expected to do, so it's a bit too contrived to use here. ISomeInterface并没有真正告诉我应该如何做的事情,因此在这里使用它有点太虚构了。

If a member is applicable to the interface, put it on the interface. 如果成员适用于该接口,请将其放在接口上。 If it's not, don't. 如果不是,那就不要。 That's really all there is to it. 这就是全部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM