drizzie
drizzie

Reputation: 3361

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?

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.

Upvotes: 1

Views: 58

Answers (1)

David
David

Reputation: 218808

Well, semantically what is a 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. 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.)

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.

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.

Upvotes: 4

Related Questions