golang / mock

GoMock is a mocking framework for the Go programming language.
Apache License 2.0
9.26k stars 608 forks source link

Suggestion: add a var declaration to document the matched interface #1

Closed rickb777 closed 9 years ago

rickb777 commented 9 years ago

I have a suggestion that the generated mock implementation code could include a var that illustrates the implemented interface.

This has become moderately widespread idiomatic practice, mostly for the purpose of documenting a type that matches an interface. Because Go doesn't include explicit syntax matching types to interfaces (and it doesn't need to, which is a good thing), this idiomatic practice has emerged instead.

An example is most useful here. Suppose I want to mock net/http/ResponseWriter. Using mockgen, I get

// Mock of ResponseWriter interface
type MockResponseWriter struct {
    ctrl     *gomock.Controller
    recorder *_MockResponseWriterRecorder
}

My suggestion is that mockgen should also generate this:

var _ *http.ResponseWriter = &MockResponseWriter{}

it would be clear to anyone reading the code that there is an implied 'implements' relationship between the type MockResponseWriter and the interface ResponseWriter. We know this because the compiler type-checks the var declaration in a way that guarantees it to be true (given that the compiler is successful). The var introduces an unnamed variable that is never used; presumably the compiler can notice that it's unused and eliminate it from the binary code.

rickb777 commented 9 years ago

Here is another example of use of this practice: golang/net/icmp/endpoint.go line 17

var _ net.PacketConn = &PacketConn{}
dsymonds commented 9 years ago

It's a nice idea, but unfortunately doesn't work in the general situation because it then requires the mock package to depend on the package holding the interface being mocked. Usually that wouldn't be a big deal, but there are situations where that package can be quite bulky, and adding a dependency edge just for this would be the wrong tradeoff.