One of the reddit suggestions in response to my entry on using type assertions to reach through interfaces noted that you could embed one interface inside another one, effectively extending the interface that you embed, so my
Closer
interface could have been:
type ConnCloser interface {
net.Conn
CloseWrite() error
}
When I saw this my instinctive reaction was that this was wrong for my situation; since then I've spent some time thinking about why I feel that way. My conclusion is that I think I have good reasons but I may be wrong.
Simplifying, the dividing point for me is whether all of the values I'm dealing with would be instances of the new interface, for example if I was writing code that only dealt with TCP and Unix stream sockets. In that situation my life would be simpler if I immediately converted the
net.Conn
values into
ConnCloser
values and then had the rest of my code deal with the latter (freely calling
.CloseWrite()
when it wanted to). What I'm doing is converting
net.Conn
values into what they really are, which is values that have a wider interface.
But if not all of the values I'm dealing with are convertible and if I'm only doing the conversion in one spot (and only once), extending
net.Conn
doesn't feel like an accurate description of what I'm doing. I'm just fishing through it to see if I can call another routine and then immediately calling that routine. Using just an interface with
CloseWrite()
makes my actual intentions clear.
I'd feel different if I was passing the converted values around between functions or storing them in something. The issue here is that such functions don't really want to accept anything that simply has a
CloseWrite()
method with the right signature; they want to deal specifically with
net.Conn
values that also have that method. A bare
Closer
interface that only specifies a
CloseWrite()
method is too broad an allowance for what I actually mean and thus would be the wrong approach. (At this point I start waving my hands vaguely.)
The more I think about it the less I'm sure what proper Go style should be here, and I have to admit that part of my feelings against
ConnCloser
are based purely on it having another line that doesn't do anything in my original situation (I'm often a terseness person).