The interfaces portion of Golang CodeReviewComments states:
Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values. The implementing package should return concrete (usually pointer or struct) types: that way, new methods can be added to implementations without requiring extensive refactoring.
Yet, Go's context.go module both defines the Context interface and implements it for type emptyCtx int and type cancelCtx struct.
Note, the portion listed above says they "generally" belong in the package that uses values of the interface type — so I understand that this is not a strict rule.
However, I am curious as to what the criteria is that makes it OK for them to do this in the context package.
Also, this assumes CodeReviewComments is a canonical resource for Go code reviews and style guide.
Defining implementations of an interface in the same package is actually pretty common, especially when implementing a strategy pattern or chain of responsibility(like context).
Take the net package for example, it defines the Listener interface, but also TCPListener, UDPListener, and UnixListener. In this case it would be illogical to place the functionality in another package.
The io package does a similar thing with the readers and writers.
Another handy pattern is to define a function alias for interfaces which only have 1 function. Like how HandlerFunc implements Handler, allowing users to cast closures as HandlerFunc so they don't have to define their own type, which is much more work.
Related
There are some common interfaces in Go's standard library, e.g, the io.Closer:
type Closer interface {
Close() error
}
If I would want to define an interface in my code that has a Close method, would I embed io.Closer like this:
type example interface {
io.Closer
// ... some other functions or embedded types
}
or would I just define the function itself like:
type example interface {
Close() error
// ... some other functions or embedded types
}
Is there any best practice for this?
For such common and simple interfaces I would definately embed the one from the standard lib (such as io.Closer, io.Reader and io.ByteReader).
But not any interface type. In general interfaces should be defined where they are needed. Embedding any interface defined in other packages (including the standard library) has the danger of failing to implicitly implement them if they are changed or extended.
The "owner" (definer) of the package may change it (e.g. extend it with a new method) and properly update all its types implementing it, so the package can continue to work from the outside, but obviously the package owner will not update your implementations.
For example the reflect.Type interface type had no Type.ConvertibleTo() method back in Go 1.0, it was added in Go 1.1. The same thing may happen: interfaces in the standard lib may get altered or extended in future Go versions, resulting in your existing code failing to implement them.
What's the difference between small, common interfaces and the "rest"? The bigger the interface, the weaker the abstraction – so goes the Go proverb. Small interfaces like io.Closer and io.Reader capture a tiny yet important functionality. They are so common, "every" library tries to implement them, every utility functions build upon them. I don't ever expect them to change. If there will be a reason to change / extend them, they will be rather added as new interfaces. Not like bigger interfaces where abstraction is harder to capture accurately. They have a better chance to change / evolve over time.
I'm learning Golang and as an exercise in using interfaces I'm building a toy program. I'm having some problem trying to use a type that "should implement" two interfaces - one way to solve that in C++ and Java would be to use inheritance(there are other techniques, but I think that is the most common). As I lack that mechanism in Golang, I'm not sure how to proceed about it. Below is the code:
var (
faces = []string{"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}
suits = []string{"Hearts", "Diamonds", "Spades", "Clubs"}
)
type Card interface {
GetFace() string
GetSuit() string
}
type card struct {
cardNum int
face string
suit string
}
func NewCard(num int) Card {
newCard := card{
cardNum: num,
face: faces[num%len(faces)],
suit: suits[num/len(faces)],
}
return &newCard
}
func (c *card) GetFace() string {
return c.face
}
func (c *card) GetSuit() string {
return c.suit
}
func (c *card) String() string {
return fmt.Sprintf("%s%s ", c.GetFace(), c.GetSuit())
}
What I'm trying to achieve:
I would like to hide my struct type and only export the interface so that the clients of the code use only the "Card" interface
I would like to have a string representation of the struct, hence the implementation of the interface with the "String()" method in order to be able to call "fmt.Println()" on instantiations of my struct
The problem comes when I'm trying to use a new card though the "Card" interface and also trying to get the string representation. I cannot pass the interface as the parameter of the implementation of the "String()" method as there is a compiler error which is related to the addressability of an interface at the core language level(still digging through that documentation). The very simple example of testing exposes the issue:
func TestString(t *testing.T) {
card := NewCard(0)
assert.EqualValues(t, "AceHearts ", card.String(), " newly created card's string repr should be 'AceHearts '")
}
The compiler tells me, for good reason, that "card.String undefined (type card has no field or method string)". I could just add the "String()" method to my "Card" interface, but I do not find that to be clean: I have other entities implemented with the same model and I would have to add that redundancy everywhere; there is already an interface with that method.
What would be a good solution for the above issue that I'm having?
Edit:(to address some of the very good comments)
I do not expect to have another implementation of the Card interface; I'm not sure I grasp why would I want to do that, that is change the interface
I would like to have the Card interface to hide away implementation details and for the clients to program against the interface and not against the concrete type
I would like to always have access to the String() interface for all clients of the "card struct" instantiations(including the ones instantiated via the Card interface). I'm not interested in having clients only with the String interface. In some other languages this can be achieved by implementing both interfaces - multiple inheritance. I'm not saying that is good or wrong, or trying to start a debate about that, I'm just stating a fact!
My intent is to find out if the language has any mechanism to fulfill those requirements simultaneously. If that is not possible or maybe from the point of view of the design the problem should be tackled in a different manner, then I'm ready to be educated
Type assertions are very verbose and explicit and would expose implementation details - they have their places but I do not think they are appropriate in the situation I have
I should go over some prefacing points first:
Interfaces in Go are not the same as interfaces in other languages. You shouldn't assume that every idea from other languages should transfer over automatically. A lot of them don't.
Go has neither classes nor objects.
Go is not Java and Go is not C++. It's type system is significantly and meaningfully different than those languages.
From your question:
I would like to have the Card interface to hide away implementation details and for the clients to program against the interface and not against the concrete type
This is the root of your other problems.
As mentioned in the comments, I see this in multiple other packages and regard it as a particularly pesky anti-pattern. First, I will explain the reasons why this pattern is "anti" in nature.
Firstly and most pertinently, this point is proven by your very example. You employed this pattern, and it has resulted in bad effects. As pointed out by mkopriva, it has created a contradiction which you must resolve.
this usage of interfaces is contrary to their intended use, and you are not achieving any benefit by doing this.
Interfaces are Go's mechanism of polymorphism. The usage of interfaces in parameters makes your code more versatile. Think of the ubiquitous io.Reader and io.Writer. They are fantastic examples of interfaces. They are the reason why you can patch two seemingly unrelated libraries together, and have them just work. For example, you can log to stderr, or log to a disk file, or log to an http response. Each of these work exactly the same way, because log.New takes an io.Writer parameter, and a disk file, stderr, and http response writer all implement io.Writer. To use interfaces simply to "hide implementation details" (I explain later why this point fails), does not add any flexibility to your code. If anything, it is an abuse of interfaces by leveraging them for a task they weren't meant to fulfill.
Point / Counterpoint
"Hiding my implementation provides better encapsulation and safety by making sure all the details are hidden."
You are not achieving any greater encapsulation or safety. By making the struct fields unexported (lowercase), you have already prevented any clients of the package from messing with the internals of your struct. Clients of the package can only access the fields or methods that you have exported. There's nothing wrong with exporting a struct and hiding every field.
"Struct values are dirty and raw and I don't feel good about passing them around."
Then don't pass structs, pass pointers to struct. That's what you're already doing here. There's nothing inherently wrong with passing structs. If your type behaves like a mutable object, then pointer to struct is probably appropriate. If your type behaves more like an immutable data point, then struct is probably appropriate.
"Isn't it confusing if my package exports package.Struct, but clients have to always use *package.Struct? What if they make a mistake? It's not safe to copy my struct value; things will break!"
All you realistically have to do to prevent problems is make sure that your package only returns *package.Struct values. That's what you're already doing here. A vast majority of the time, people will be using the short assignment :=, so they don't have to worry about getting the type correct. If they do set the type manually, and the choose package.Struct by accident, then they will get a compilation error when trying to assign a *package.Struct to it.
"It helps to decouple the client code from the package code"
Maybe. But unless you have a realistic expectation that you have multiple existent implementations of this type, then this is a form of premature optimization (and yes it does have consequences). Even if you do have multiple implementations of your interface, that's still not a good reason why you should actually return values of that interface. A majority of the time it is still more appropriate to just return the concrete type. To see what I mean, take a look at the image package from the standard library.
When is it actually useful?
The main realistic case where making a premature interface AND returning it might help clients, is this:
Your package introduces a second implementation of the interface
AND clients have statically and explicitly (not :=) used this data type in their functions or types
AND clients want to reuse those types or functions for the new implementation also.
Note that this wouldn't be a breaking API change even if you weren't returning the premature interface, as you're only adding a new type and constructor.
If you decided to only declare this premature interface, and still return concrete types (as done in the image package), then all the client would likely need to do to remedy this is spend a couple minutes using their IDE's refactor tool to replace *package.Struct with package.Interface.
It significantly hinders the usability of package documentation
Go has been blessed with a useful tool called Godoc. Godoc automatically generates documentation for a package from source. When you export a type in your package, Godoc shows you some useful things:
The type, all exported methods of that type, and all functions that return that type are organized together in the doc index.
The type and each of its methods has a dedicated section in the page where the signature is shown, along with a comment explaining it's usage.
Once you bubble-wrap your struct into an interface, your Godoc representation is hurt. The methods of your type are no longer shown in the package index, so the package index is no longer an accurate overview of the package as it is missing a lot of key information. Also, each of the methods no longer has its own dedicated space on the page, making it's documentation harder to both find and read. Finally it also means that you no longer have the ability to click the method name on the doc page to view the source code. It's also no coincidence that in many packages that employ this pattern, these de-emphasized methods are most often left without a doc comment, even when the rest of the package is well documented.
In the wild
https://pkg.go.dev/github.com/zserge/lorca
https://pkg.go.dev/github.com/googollee/go-socket.io
In both cases we see a misleading package overview, along with a majority of interface methods being undocumented.
(Please note I have nothing against any of these developers; obviously every package has it's faults and these examples are cherry picked. I'm also not saying that they had no justification to use this pattern, just that their package doc is hindered by it)
Examples from the standard library
If you are curious about how interfaces are "intended to be used", I would suggest looking through the docs for the standard library and taking note of where interfaces are declared, taken as parameters, and returned.
https://golang.org/pkg/net/http/
https://golang.org/pkg/io/
https://golang.org/pkg/crypto/
https://golang.org/pkg/image/
Here is the only standard library example I know of that is comparable to the "interface hiding" pattern. In this case, reflect is a very complex package and there are several implementations of reflect.Type internally. Also note that in this case, even though it is necessary, no one should be happy about it because the only real effect for clients is messier documentation.
https://golang.org/pkg/reflect/#Type
tl;dr
This pattern will hurt your documentation, while accomplishing nothing in the process, except you might make it slightly quicker in very specific cases for clients to use parallel implementations of this type that you may or may not introduce in the future.
These interface design principles are meant for the benefit of the client, right? Put yourself in the shoes of the client and ask: what have I really gained?
Not entirely sure if this is what you are looking for but you could try embedding the other interface in Card interface as shown below.
type Printer interface {
String() string
}
type Card interface {
Printer // embed printer interface
GetFace() string
GetSuit() string
}
Interface Card hasn't method String, it doesn't matter, that underlying type card have it, because method is hidden from you (unless you access it via reflection).
Adding String() string method to Card will solve problem:
type Card interface {
GetFace() string
GetSuit() string
String() string
}
The go language does not have subtype polymorsphism. Therefore, the pattern you want to achieve is not encouraged by the very foundations of the language. You may achieve this undesirable pattern by composing structs and interfaces, though.
I have 3 classes, which have several operation steps implemented in different functions. For example,
func ExternalAPI1() error
func ExternalAPI2(s string)
func internalProcess1() error
func internalProcess2(s []string) error
func internalProcess3(d int) error
For the internalProcessx, they're internal functions which may not be invoked by other classes, but these functions do have identical signatures.
Should I generate an interface for them with only ExternalAPI1 and ExternalAPI2 included? or should I include all these 5 functions in the interface?
tl;dr: don't worry about interfaces when creating structs, worry about interfaces when creating functions that would consume them.
The question overlooks an important underlying question: do you need an interface at all? I.e., is something going to accept values of the interface type, and operate on them without knowledge of the underlying type? If so, what methods will it call on the value? Those are the methods that should be in the interface.
Remember that Go uses duck interfaces; therefor, interfaces should be defined to suit the consumer, not the implementation. In fact, they should generally be defined alongside the consumer, not the implementation, because the implementation doesn't need to know anything about the interfaces it implements.
In Go, when a function or method can operate on "anything that implements method X", then alongside that function or method, you can define an "Xer" interface with that method signature. This allows anything to be passed to that function which meets the interface, and the function doesn't need to worry about what the underlying type is.
If you want the compiler to enforce that all structs which implement the interface have the unexported methods too, the unexported methods can certainly be included in the interface.
reflect.Type is an example from the stdlib (see here, godoc notes that the interface contains unexported methods)
An interface describes the methods required to perform a certain action. In your case, this is definitely the following:
type API interface {
ExternalAPI1() error
ExternalAPI2(s string)
}
However, do note that this does not limit the use of non-exported methods when using your struct (not class) directly from the same package.
I'm just start learning Go, most of my background came from Java, Ruby.
I just wonder that, from my example, why Go language designer intentionally design to not specify an interface type when implement an interface. So that if someone accidentally try to assign an object to an interface that match a signature but doesn't intend to implement that interface, that would lead to be a bug and cannot be catch at a compile time.
You can try at this: https://play.golang.org/p/1N0kg7m4eE
package main
import "fmt"
type MathExpression interface {
calculate() float64
}
type AreaCalculator interface {
calculate() float64
}
type Square struct {
width, height float64
}
//This implementation intend to implement AreaCalculator interface
func (s Square) calculate() float64 {
return s.width * s.height
}
func main() {
//Suppose that a developer got this object from
//somewhere without a knowledge that object is a Square struct
mysteryStruct := Square{width: 4, height: 3}
var areaCalculator AreaCalculator = mysteryStruct
fmt.Println("Area of something:", areaCalculator.calculate())
var mathExpression MathExpression = mysteryStruct
fmt.Println("This should not work:", mathExpression.calculate())
}
One advantage of "implicitly satisfied" interfaces (ones where types don't need to explicitly declare that they implement them) is that interfaces can be created after the fact. You can see several types that have a method in common, perhaps in different packages, and decide to write a function that can accept any of them by calling for a new interface that specifies that method.
Also, Go's approach to interfaces lets you write an abstraction of the behavior of a type in an existing package, without modifying the original package. The first example that comes to my mind is the File interface in the net/http package:
type File interface {
io.Closer
io.Reader
io.Seeker
Readdir(count int) ([]os.FileInfo, error)
Stat() (os.FileInfo, error)
}
It represents a file that can by served by an http.FileServer. Normally it is an os.File, but it could be anything that fulfills the interface. For example, I think someone has made an implementation that serves files out of a zip archive.
Since the net/http package is defined in the standard library, it might have been possible to explicitly declare that os.File implements http.File—but it would have made the os package depend on the net/http package. This is a circular dependency, because net/http depends on os.
In an inheritance-based language, someone who was trying to do this would probably just give up on using an interface, and make http.FileServer require that all files be subclasses of os.File. But this would be a pain, because they wouldn't need any of the implementation of an os.File; they would just be inheriting from it to satisfy the type system.
The example in the OP works because of a poorly-chosen method name. It is not at all clear what a Square's calculate method should return. Its area? Its perimeter? Its diagonal? If the method were named CalculateArea, which would be the idiomatic name for the single method in an interface named AreaCalculator, it would not be possible to confuse an AreaCalculator and a MathExpression.
Go uses implicit interfaces, it means that type implements interface if it has all functions required by interface. Note that you don't have to declare in code that type implements interface (as in Java).
Such language design have good and bad consequences:
type can implement interface by accident (this happened in your example). Actually it happens very rarely so IMO it is not a big problem.
without interface declaration in code you don't know which interfaces your type implements. This problem can be solved by using good IDEs.
you can easily create adapters and similar design patterns
you can easily create mocks
more readable code (type declaration is very simple in go)
One benefit of this approach is inversion of dependencies. In typical languages with static type systems, you have source level dependency from implementation to interface. Which means you can't deploy them separately. With implicit interfaces you have no source level dependency and implementation module can be deployed/developed/build without module containing interface. This gives you flexibility usually reserved for dynamic type systems.
From the Go documentation on method declarations:
The receiver type must be of the form T or *T where T is a type name. T is called the receiver base type or just base type. The base type must not be a pointer or interface type and must be declared in the same package as the method.
Can anyone give me some insight on why this might be? Are there any other (statically typed) languages that would allow this? I really want to define methods on an interface so I can treat any instance of a given interface type as another. For example (stealing the example from the Wikipedia article on the Template Method Pattern) if the following was valid:
type Game interface {
PlayOneGame(playersCount int)
}
type GameImplementation interface {
InitializeGame()
MakePlay(player int)
EndOfGame() bool
PrintWinner()
}
func (game *GameImplementation) PlayOneGame(playersCount int) {
game.InitializeGame()
for j := 0; !game.EndOfGame(); j = (j + 1) % playersCount {
game.MakePlay(j)
}
game.PrintWinner()
}
I could use any instance implementing "GameImplementation" as a "Game" without any conversion:
var newGame Game
newGame = NewMonopolyGame() // implements GameImplementation
newGame.PlayOneGame(2)
UPDATE: the purpose of this was to try and achieve all the benefits of abstract base classes without all the coupling that goes with an explicit hierarchy. If I wanted to define a new behaviour PlayBestOfThreeGames, abstract base classes would require me to change the base class itself - whereas here I just define one more method on top of the GameImplementation interface
It's probably for the same reason you can't define methods on interfaces in Java.
An interface is meant to be a description of a part of, or the whole of, the external interface for a set of objects and not how they implement the underlying behavior. In Java you would probably use an abstract class if you need parts of the behavior to be pre-defined but I think the only way to do that in Go is to use functions rather than methods.
I believe that for your example the more Go idiomatic code would be something like this:
type GameImplementation interface {
InitializeGame()
MakePlay(player int)
EndOfGame() bool
PrintWinner()
}
func PlayOneGame(game GameImplementation, playersCount int) {
game.InitializeGame()
for j := 0; !game.EndOfGame(); j = (j + 1) % playersCount {
game.MakePlay(j)
}
game.PrintWinner()
}
Where PlayOneGame and any specific game implementation are probably living in different packages.
Here is some discussion on golang-nuts
In answer to your question of whether there are other statically typed languages that allow this: yes, most. Any language with multiple inheritance allows classes to have arbitrary mixes of abstract and concrete methods. Also, see Scala's traits, which are like Java's interfaces but can have concrete methods. Scala also has structural types, which are really all that Go's interfaces are.
What you're describing as in Interface is really what might elsewhere be referred to as an abstract class -- that is, a class with some methods defined but not all, which must be subclassed in order to be instantiated.
However, Go doesn't have any concept of a class hierarchy -- the whole type structure is flat. Each method on a class is defined for that class specifically, not on any parent class or subclass or interface. This was a conscious design decision, not an omission.
In Go, an Interface is therefore not a component of a type hierarchy (as there is no such thing). Instead, it is simply an ad-hoc specification of the set of methods which must be implemented for a given purpose. That's all. They're a stand-in for dynamic typing whereby you can declare ahead of time which functions on a given type you'll be using -- then any variable who's type satisfies those requirements can be used.
This makes it impossible to use patterns like Generics with Go, and Rob Pike has said at a conference that this might be changed in the future if someone can come with a an elegant implementation and a compelling use case. But that remains yet to be seen.
First, it's important to notice that types implement interfaces implicitly — that is, interfaces are "duck types". Any type that provides the methods required by the interface is assignable to a variable of the interface type, without any cooperation from the original type. This is different from, say, Java or C# where a class that implements an interface has to declare its intention to implement the interface, in addition to actually providing the methods.
Go also has a pretty strong tendency against "action at a distance". For example, even though methods are declared separately from types, it's illegal to declare a method in a different package from its receiver type. You can't just go adding methods to os.File.
If interfaces could provide methods (making them traits/roles) then any type that implemented an interface would gain a bunch of new methods out of nowhere. Someone reading the code and seeing those methods used probably have a hard time figuring out where they came from.
There's a problem with fragility — change the signature of a method that's required by an interface, and a bunch of other methods appear or disappear. In the case where they disappeared, it's not obvious where they "would have" come from. If types had to declare their intention to implement an interface then breaking the contract would prompt an error (and "accidentally" implementing an interface does nothing), but when interfaces are satisfied implicitly things are trickier.
Worse, there could be name conflicts — an interface provides a method with the same name as a method provided by a type that implements that interface, or two interfaces both provide a method with the same name, and some type happens to implement both of those interfaces. Resolving that conflict is the kind of complication that Go really likes to avoid, and in a lot of cases there is no satisfying resolution.
Basically, it would be really cool if interfaces could provide methods — roles as composable units of behavior are cool, and mesh well with Go's composition-over-inheritance philosophy — but actually doing it would be too complicated and too action-at-a-distance-y for Go to contemplate.