Software Engineering
c# design interfaces third-party-libraries inversion-of-control
Updated Wed, 10 Aug 2022 00:15:09 GMT

Should I write an interface API before an implementation?

I've been delving into more "organized" programming recently and I've been learning that I should be programming to an interface, not an implementation. With that in mind, would it be better to "sketch" out a project in interfaces before writing the implementation for it where possible?

And if this is the case, in the case of using 3rd party libraries (ie Lidgren), should I be wrapping those in interfaces as well and resolve them through IOC containers, or is it OK to expose them to the interfaces?


Unfortunately, you'll find this often boils down to personal preference.

What you've described so far, though, seems good. In fact, if you wanted to (and I recommend it) you could use the following approach:

  1. Write your application skeleton as Interfaces, abstract classes (stubbed), and classes (also stubbed)
  2. Write your tests against those interfaces and stubs (they will fail for now)
  3. Write your implementations (your tests will start passing as you finish your implementation)

You're focusing on trying to write more "organized" code. Following TDD will help you with this.

Some extra points:

  • IoC containers are convenient. Use them and DI as much as you can.
  • Do wrap 3rd party libraries. This will loosen the coupling between your code (code you control) and 3rd party code (code you don't control)

Comments (5)

  • +1 – This was what I had originally thought but I was told it would violate the YAGNI principle. The problem that I find with a lot of my projects that never get finished is that they rapidly become un-maintainable with the amount of blob code I've written, because I don't organize it properly or plan out my plan of attack. — Dec 06, 2013 at 09:58  
  • +0 – which part would violate YAGNI? — Dec 06, 2013 at 09:58  
  • +0 – Wrapping 3rd party libraries. — Dec 06, 2013 at 09:59  
  • +2 – I guess it boils down to: What are the odds of the 3rd party library changing? If there is a 0% chance of this, then sure YAGNI. But, that's rarely the case. Also, wrapping your 3rd party libs may make your other code more easy to unit test (if, for example, you couldn't mock out the 3rd party library) — Dec 06, 2013 at 10:01  
  • +1 – @DanPantry: Wrapping third party libraries isn't a YAGNI violation, but a much needed protection against "third party library infestation of your own code". It is not just about being able to swap out a library, but as MetaFight also says a defense against changes in newer versions of the library which would otherwise require changes throughout your own code. By wrapping the library (and especially its specific types: classes, enums, structs etc), you insulate your own code and have a single point to change when the library changes (for whatever reason). — Dec 06, 2013 at 11:13