"is it the best practice to extract an interface for every class?" Code Answer


after revisiting this answer, i've decided to amend it slightly.

no, it's not best practice to extract interfaces for every class. this can actually be counterproductive. however, interfaces are useful for a few reasons:

  • test support (mocks, stubs).
  • implementation abstraction (furthering onto ioc/di).
  • ancillary things like co- and contra-variance support in c#.

for achieving these goals, interfaces are considered good practice (and are actually required for the last point). depending on the project size, you will find that you may never need talk to an interface or that you are constantly extracting interfaces for one of the above reasons.

we maintain a large application, some parts of it are great and some are suffering from lack of attention. we frequently find ourselves refactoring to pull an interface out of a type to make it testable or so we can change implementations whilst lessening the impact of that change. we also do this to reduce the "coupling" effect that concrete types can accidentally impose if you are not strict on your public api (interfaces can only represent a public api so for us inherently become quite strict).

that said, it is possible to abstract behaviour without interfaces and possible to test types without needing interfaces, so they are not a requirement to the above. it is just that most frameworks / libraries that you may use to support you in those tasks will operate effectively against interfaces.

i'll leave my old answer for context.

interfaces define a public contract. people implementing interfaces have to implement this contract. consumers only see the public contract. this means the implementation details have been abstracted away from the consumer.

an immediate use for this these days is unit testing. interfaces are easy to mock, stub, fake, you name it.

another immediate use is dependency injection. a registered concrete type for a given interface is provided to a type consuming an interface. the type doesn't care specifically about the implementation, so it can abstractly ask for the interface. this allows you to change implementations without impacting lots of code (the impact area is very small so long as the contract stays the same).

for very small projects i tend not to bother, for medium projects i tend to bother on important core items, and for large projects there tends to be an interface for almost every class. this is almost always to support testing, but in some cases of injected behaviour, or abstraction of behaviour to reduce code duplication.

By farrellmr on June 10 2022

Answers related to “is it the best practice to extract an interface for every class?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.