Is it the best practice to extract an interface for every class?

后端 未结 13 2512
我在风中等你
我在风中等你 2020-12-04 17:43

I have seen code where every class has an interface that it implements.

Sometimes there is no common interface for them all.

They are just there and they are

相关标签:
13条回答
  • 2020-12-04 18:19

    No.

    Interfaces are good for classes with complex behaviour, and are especially handy if you want to be able to create a mock or fake implementation class of that interface for use in unit tests.

    But, some classes don't have a lot of behaviour and can be treated more like values and usually consist of a set of data fields. There's little point in creating interfaces for classes like this because doing so would introduce unnecessary overhead when there's little point in mocking or providing alternative implementations of the interface. For example, consider a class:

    class Coordinate
    {
      public Coordinate( int x, int y);
      public int X { get; }
      public int y { get; }
    }
    

    You're unlikely to want an interface ICoordinate to go with this class, because there's little point in implementing it in any other way than simply getting and setting X and Y values.

    However, the class

    class RoutePlanner
    {
       // Return a new list of coordinates ordered to be the shortest route that
       // can be taken through all of the passed in coordinates.
       public List<Coordinate> GetShortestRoute( List<Coordinate> waypoints );
    }
    

    you probably would want an IRoutePlanner interface for RoutePlanner because there are many different algorithms that could be used for planning a route.

    Also, if you had a third class:

    class RobotTank
    {
       public RobotTank( IRoutePlanner );
       public void DriveRoute( List<Coordinate> points );
    }
    

    By giving RoutePlanner an interface, you could write a test method for RobotTank that creates one with a mock RoutePlanner that just returns a list of coordinates in no particular order. This would allow the test method to check that the tank navigates correctly between the coordinates without also testing the route planner. This means you can write a test that just tests one unit (the tank), without also testing the route planner.

    You'll see though, it's quite easy to feed real Coordinates in to a test like this without needing to hide them behind an ICoordinate interface.

    0 讨论(0)
提交回复
热议问题