7

There is an emphasis on using interfaces instead of concrete types in order to make the code easier to test. I wonder though why this wasn't done for the types in the sql package like DB or Rows. In order to mock those dependencies I had to create my own interfaces so that I could write unit tests (not integration tests). Aren't DB facing code supposed to be tested that way?

3
  • 1
    Anybody can create interfaces for any type, in Go. It means there's zero need to declare an interface that you don't use. As you noticed, the fact there wasn't any pre-existing interface didn't prevent you from creating the ones you wanted. Commented Dec 29, 2016 at 16:23
  • Sure, I get that. But I come across many gophers emphasising the usage of interfaces upfront to make it easier for others to mock the concrete types. Maybe I'm overthinking this. Thanks. Commented Dec 29, 2016 at 16:32
  • 2
    @AmirKeibi: Interfaces make mocking a lot easier, true enough, but that doesn't mean package maintainers are supposed to create fully interface-based packages. There's a package out there that allows you to mock database/sql stuff quite easily: go-sqlmock, maybe take a look at that? Commented Dec 29, 2016 at 16:55

1 Answer 1

1

Exposing interfaces in your public API instead of concrete types increases the risk of breaking other peoples code when you add methods to the interface.

See for example os.File. If os.File was an interface it would be an interface with 17 public methods. Adding an 18th method would break everyone who defined their own types that implemented the os.File interface. In contrast, adding an 18th method to the current os.File struct won't break any methods taking an io.Reader, io.Writer or any other interface that defines a subset of the methods of an os.File. It also won't break test code which mocks these io.Reader and io.Writer interfaces.

So expose an interface in your public API if you want other people to define their own implementations of them. Otherwise expose a concrete type and let people define their own interfaces implemented by your concrete type using only the subset of methods they need.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.