Skip to content

Commit 9f265e1

Browse files
authored
Add a paragraph about interface pollution (quii#704)
1 parent b4b789b commit 9f265e1

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

anti-patterns.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,16 @@ What are the signals here? _Listen_, complicated tests `==` complicated code. Wh
105105

106106
If you have declared an `interface` that has many methods, that points to a leaky abstraction. Think about how you could define that collaboration with a more consolidated set of methods, ideally one.
107107

108+
#### Interface pollution
109+
110+
As a Go proverb says, *the bigger the interface, the weaker the abstraction*. If you expose a huge interface to the users of your package, you force them to create in their tests a stub/mock that matches the entire API, providing an implementation also for methods they do not use (sometimes, they just panic to make clear that they should not be used). This situation is an anti-pattern known as [interface pollution](https://rakyll.org/interface-pollution/) and this is the reason why the standard library offers you just tiny little interfaces.
111+
112+
Instead, you should expose from your package a bare struct with all relevant methods exported, leaving to the clients of your API the freedom to declare their own interfaces abstracting over the subset of the methods they need: e.g [go-redis](https://github.com/redis/go-redis) exposes a struct (`redis.Client`) to the API clients.
113+
114+
Generally speaking, you should expose an interface to the clients only when:
115+
- the interface consists of a small and coherent set of functions.
116+
- the interface and its implementation need to be decoupled (e.g. because users can choose among multiple implementations or they need to mock an external dependency).
117+
108118
#### Think about the types of test doubles you use
109119

110120
- Mocks are sometimes helpful, but they're extremely powerful and therefore easy to misuse. Try giving yourself the constraint of using stubs instead.

0 commit comments

Comments
 (0)