Coding Zealotry: Class Interfaces

Share On

In a previous article entitled “The Religious Zealotry of Coding Best Practice”, we looked at how some best practices are implemented blindly, even though the costs outweigh the benefits where the practice is actually implemented.

In this article we’ll take a brief look at class interfaces.

It Starts Simple

So here’s a classic service class in C#:

public class CarCreator
   public Car CreateCar(string name)
       return new Car { Name = name };

It’s simple, it does what it says it’s going to do, it’s easy to read, and clearly easy to add onto.

But What If…

At this point the abstractionists step in, mindful of their grounding in “best practice”. So we get:

public class ICarCreator
   Car CreateCar(string name);

Why did we need an interface? Inversion of control (IOC), plus unit test mocking, plus one day it will allow us to swap out the creator for another version, and … because it’s a good practice.

Counting the Cost

Coding against interfaces doesn’t come for free. Here are a few gotchas:

  • Every new public method you add requires two pieces of work
  • Every refactoring of public methods requires changes in two places
  • Possibly updating two sets of comments
  • Hitting the interface method instead of the implementation when using VS or Resharper shortcuts
  • Hitting the interface method when stepping through on debugging
  • Adding IOC redirection
  • Adding mocking on affected tests

Obviously tools like Resharper assist with some of these tasks. The fact remains: there is indeed a cost, so if you’re incurring the cost, you better at least match it with a benefit, otherwise you’re burning money. In the case of mocking, for example, I have to ask why you can’t just allow the call to go through to the actual implementation of the class instead of having to mock it out?

Put Requirements at the Wheel

SteeringWheelObviously we know there is a time for interfaces, but rather wait for the time to come. When you find the need to abstract a class, using a tool like Resharper to pull out the common methods to an interface is very straight-forward.

I heard a talk recently where the speaker referred to the fact that we design for code re-use, but we seldom actually get around to it, usually rewriting a system instead. In fact, this whole idea of swapping out a layer is very rarely implemented, and the pain of adding extra structure and work to accommodate it is actually rarely justified.

Share On

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
× How can I help you?