Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using explicit interfaces to ensure programming against an interface

I have seen arguments for using explicit interfaces as a method of locking a classes usage to that interface. The argument seems to be that by forcing others to program to the interface you can ensure better decoupling of the classes and allow easier testing.

Example:

public interface ICut
{
    void Cut();
}
public class Knife : ICut
{
    void ICut.Cut()
    {
        //Cut Something
    }
}

And to use the Knife object:

ICut obj = new Knife();
obj.Cut();

Would you recommend this method of interface implementation? Why or why not?

EDIT: Also, given that I am using an explicit interface the following would NOT work.

Knife obj = new Knife();
obj.Cut();
like image 591
chills42 Avatar asked Oct 07 '08 14:10

chills42


1 Answers

To quote GoF chapter 1:

  • "Program to an interface, not an implementation".
  • "Favor object composition over class inheritance".

As C# does not have multiple inheritance, object composition and programming to interfaces are the way to go.

ETA: And you should never use multiple inheritance anyway but that's another topic altogether.. :-)

ETA2: I'm not so sure about the explicit interface. That doesn't seem constructive. Why would I want to have a Knife that can only Cut() if instansiated as a ICut?

like image 108
erlando Avatar answered Sep 26 '22 03:09

erlando