go-proverbs / go-proverbs.github.io

Inspired by @rob_pike talk at Gopherfest SV 2015
MIT License
328 stars 21 forks source link

I could not find the proverb "Accept Interfaces Return Struct in Go" here #37

Open cyantarek opened 4 years ago

robpike commented 4 years ago

I'm not a great fan of that one. It's subtle and tricky to explain compactly. And although popular, it's not often easy to apply well. Plus: Why structs? There are many other concrete types in Go.

cyantarek commented 4 years ago

Then this can be "Accept Interfaces Return Concrete Types"

robpike commented 4 years ago

I still don't favor this one. It's very hard to be clear about where it applies, and it often doesn't.

invidian commented 2 years ago

It seems to me that one example where this does not apply is when you want to make user use a constructor function, rather than making the struct exported. If you return unexported struct, the function won't be picked up by documentation tool and returning an exported struct may lead to mis-use (e.g. constructing struct "by hand", then calling their methods, without proper initialization). This seems like a practice done with defensive programming.

Accepting interfaces (or maybe defining interfaces on the receiver side) would still be worth mentioning.