Two common Go interface misuses

submited by
Style Pass
2024-10-21 07:00:04

In Go, interfaces are often misused in two ways. First, interfaces are introduced prematurely by following object-oriented patterns from languages like Java. While well-intentioned, this approach adds unnecessary complexity early in the development process.

Second, interfaces are created solely to support testing, a practice common in languages like Python that also relies heavily on mocking dependencies. While this might unblock your productivity in the short term, it weakens the expressiveness of your types and ultimately reduces code readability in the long run. This post will focus on these two issues to illustrate their impact.

The first common pitfall is the premature introduction of abstraction. In Go, however, we emphasize writing easy-to-read code rather than designing complex type hierarchies. Suppose you want to implement an in-memory cache with a Least-Frequently Used (LFU) policy. Following an abstraction-first mindset, you might start by defining an interface and a concrete type like this:

You might think this is a good idea because you anticipate having different implementations in the future, such as caches using different policies, and you want to showcase your ability to build for future flexibility from the start. This approach, however, raises two important questions you should ask yourself:

Leave a Comment