Why database types are not an interface in GO

The emphasis is on using interfaces instead of specific types to make code easier to test. I wonder why this was not done for types in the sql package, such as DB or Rows. To mock these dependencies, I had to create my own interfaces so that I could write unit tests (rather than integration tests). Should I not test this code with a DB code?

+6
source share
1 answer

Providing interfaces in your public API instead of specific types increases the risk of breaking other people's code when adding 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 the 18th method will break all those who defined their own types that implemented the os.File interface. In contrast, adding the 18th method to the current os.File structure os.File not violate any methods using io.Reader , io.Writer or any other interface that defines a subset of the os.File methods. It also does not break the test code that mocks these io.Reader and io.Writer .

This way you can open the interface in your public API if you want other people to define their own implementations. Otherwise, deduce a specific type and let people define their interfaces implemented by your specific type using only a subset of the methods they need.

0
source

Source: https://habr.com/ru/post/1013609/


All Articles