Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why database types aren't interface in GO

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?

like image 302
Amir Keibi Avatar asked Dec 29 '16 16:12

Amir Keibi


1 Answers

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.

like image 175
Johan Wikström Avatar answered Oct 05 '22 04:10

Johan Wikström