The gist https://gist.github.com/anonymous/68c3b072538ec48c2667f7db276e781b is a minimal simplified example of a repeated golang code pattern that I have encountered in an existing code base which I am trying to document. From its usage it appears to be similar to a mixin, but neither myself or any of my colleagues have actually seen this pattern before in golang. Can anyone tell me an appropriate established name for this pattern?
The gist attempts to illustrate:
- Unmodified behaviour implementation code (M's funcs) used by multiple types (A and B).
- Included by composition into a host type (A and B).
- Behaviour methods exported and accessible via a host.behaviour.method(...) call e.g. a.Formatter.FormatText(...).
- Host methods are acted upon by the behaviour.
- The behaviour holds state (private or exported) which modifies the execution of the behaviour.
- The type that has add a specific behaviour added can be used by a function needing that behaviour by passing the behaviour field e.g. b := NewB().Formatter.
- Many different behaviours can be composed into a given type (not actually shown for brevity, but you could imagine an M1, M2, M3, etc being included into A or B).
It does not seem to strictly satisfy much of the definitions for a mixin as it manipulates the host object in ways that were beyond M's knowledge when it was written (potentially modifying host state) and doesn't directly add methods to the host type:
And it doesn't seem to follow the same pattern as some self proclaimed 'golang mixins' I have found:
- https://gist.github.com/haazime/270657beb140a307a559
- https://gist.github.com/hasanozgan/2598e6abe80803e4573b
- Limited mixin-like behaviour by embedding (e.g. embedding sync.Mutex) https://groups.google.com/forum/#!topic/golang-nuts/lFWYE8UzBCg