Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wrong to make every concrete class to inherit from an interface?

This is in response to certain comments made by Zed Shaw in his blog a long while ago.

The experts will then saunter off to implement their Flaming Tower of Babel without any comments, horribly complex mock enabled tests, making sure EVERY SINGLE CLASS HAS AN INTERFACE, and ending every class with “Impl” because, well, that’s the best practice.

I use Spring and Google Guice in equal measures and I've noticed that these frameworks do use the Impl postfix but sparingly. In my code, I use interfaces everywhere because I've been told that it makes it easier to mock etc. Do I have a naive understanding of the issue ? (Perhaps mock frameworks can work with abstract classes or classes, I don't know. I have never tried) For my concrete implementations, I have chosen the Spring convention of prefixing the name of the implementation with the word Default.

e.g. BottleOpener (interface) is implemented by DefaultBottleOpener (class)

What is the best practice on this issue ?

UPDATE1 I find it useful to return an interface from a method because I can always return an anonymous class.

like image 454
Jacques René Mesrine Avatar asked Feb 18 '10 02:02

Jacques René Mesrine


2 Answers

It's more than just mocks. In the case of Spring, it's about dynamic proxies and aspect-oriented programming. That's how Spring does transactions, remoting, and aspects of all types.

I use interfaces for repositories, services, and the like, but I don't put interfaces on model objects or anything else whose implementation isn't likely to change.

Interfaces separate APIs from how they're implemented. If your implementation doesn't change, an interface doesn't make much sense.

Zed Shaw is a terrific writer and developer, but take what he says with a grain of salt. I think some of the over the top hyperbole that he indulges in is for entertainment value. He's got a point ("Don't do things just because somebody who claims to be an authority tells you it's a 'best practice'"), but the way he's saying it is part theater.

like image 190
duffymo Avatar answered Nov 15 '22 15:11

duffymo


The best practice is to:

  • Pick a convention and be consistent about it; and
  • Don't go overboard with making everything implement an interface.
like image 31
cletus Avatar answered Nov 15 '22 14:11

cletus