wiki.hjertnes.website

Interfaces

Interfaces are a structure in many programming languages. I think I have only seen them in statically typed languages. Like C#, Java, Golang, TypeScript etc.

I used to think they were kind of dumb. But I have grown to love them.

They work differently in different languages. In C#, Java, TypScript etc the interfaces a class implements are tied to it. While in Goland they are implicit.

Explicit interfaces are easier to understand, while implicit ones are much more flexible and really powerful because you can add your own eithout touch the original code. Interfaces are useful for a number of things

  • Unit Testing: you can mock the methods of a interface, making it possible to write code in a way where your unit test only care about how that class works and you can mock responses and behaviour of other stuff it uses.
  • Cleaner depdencies. If you build large micro service system you often have a bunch of shared code. So you start building some small packages to avoi duplication. Sooner or later you have a mess of dependeices between the packages etc. What you can do is to have the interfaces in one package and the implementations in another. The interfacaes are usually more stable than implementations (because bugs). In this way all the packages only need to deal with the interfaces and the service using them also need to have the implementations
  • More flexible code bases. Let's say you have an interface for your data access layer in your restful API. Then you could change databases without changing any code outside that module.