3 ms·
To take your point and run with it: in the face of evolving code, returning an interface from a function is actually more conservative than returning a struct.
by balefrost 9y ago
To take your point and run with it: in the face of evolving code, returning an interface from a function is actually more conservative than returning a struct. If you return a concrete type of some sort, then as you evolve your code, you are obligated to continue to return that specific concrete type. As your implementation of the function changes, you might want to return a different concrete type, but you are prevented from doing so. You either have to change the signature, which would break callers, or else you would need to grow that concrete type to handle all the possible ways in which it would want to represent its data.
I realize that this goes against the Go ethos of "don't think about the future; think about the now". Having said that, I don't understand why returning interfaces is seen as premature design while accepting interfaces is seen as reasonable and expected. Surely both can be examples of premature abstraction.
I'm certainly not saying that you should always return interfaces, or that returning interfaces will prevent all future refactoring pain. But working with interfaces instead of concrete types is more likely to allow your API to remain stable even as the implementation evolves.