How do you feel about using variadic functions for optional dependency injection in Go?

86 views
Skip to first unread message

todd.w...@bird.co

unread,
Feb 14, 2020, 9:28:47 AM2/14/20
to golang-nuts

So I started growing fond of a new pattern in my Go code. Not sure if it is an antipattern for go or not but here is a quick description to see what everyone thinks:


In order to properly unit test a lot of code, sometimes you have to decouple some of the dependencies. The most common (only?) way I’ve seen this done in other code bases is by passing some sort of interface and it is often called XManager. And you have to pass this manager every time you want to use the function. This makes it easy to pass a MockXManager in a unit test. However, it is very annoying to have to go through all of those steps sometimes. More recently I wanted to mock time.Sleep so that my unit tests don’t take several minutes to complete. At first I went for the tried and true YManager approach but it just felt so overengineered. At the same time I needed to mock out time.Sleep.


So a couple weeks ago I started using variadic functions to pass optional arguments. I decided last night to use this to pass an optional mock sleep method. So when you are not in unit tests you don’t have to think about it. You only have to add like 4 or 5 lines of code to set up the default argument if not supplied. In the tests I was able to pass my own sleep method that did what I needed instantly.

This works really good when you have a single thing you need to customize but it can also work well if you have multiple dependencies. In the case of multiple dependencies you can use the same approach but with a struct instead of a single mocked function. This way you can set up the default behavior without app code having to pass any manager. In unit tests you simply supply the last optional parameter.

Ben Burwell

unread,
Feb 14, 2020, 10:29:47 AM2/14/20
to todd.w...@bird.co, golang-nuts
This reminds me of the "functional options" approach:
https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis

Of course, the difference being Dave is talking about configuring a
struct type and you're talking about configuring a func type.
Reply all
Reply to author
Forward
0 new messages