DEV Community

loading...

Discussion on: The Problem with Interfaces, and how Go Fixed it

Collapse
ddekany profile image
ddekany

Not sure if the Go designers are just trolling or what... You're suggesting that the idea is that a class can implement an interface purely out of coincidence, and that's somehow useful in reality. But, if the interface was implemented accidentally, that means that the author of the implementing class didn't know what behavior the interface specifies for those methods (he/she haven't seen the API docs). So that's exactly the unfortunate case where you don't want to utilize implicit interfaces. If, however, the author of the class have implemented the interface on purpose, it's a big loss that this intent can't be expressed in the language (doing that in comments is obviously inferior; they aren't enforced or checked), as now the code is less self-documenting.

OK, there's a thin chance that both the method signatures and the specified behavior matches, purely out of blind luck, and not because the author deliberately implemented the interface. Given the certainly low chance of that happening, is it worth it to give up said self documenting capability? I mean that's quite a big sacrifice.

Collapse
dean profile image
Dean Bassett Author

First of all - Go isn't object oriented. It doesn't have classes, it has structs. It doesn't have methods, it has functions that operate on structs. OOP interfaces describe what a class is, but Go interfaces describe how a struct behaves.

It's okay to accidentally implement an interface, there's no sacrifice. Sure, you might make a door struct that might have a close() function, but in order to mess something up, you'd need to pass it into a method that clearly says it takes an io.Closer as an argument.

Also, these exceptions are still caught at compile time. If you pass a struct that doesnt match a specific interface to a function that requires that interface, it will throw a compile-time error that specifies which functions are missing from the struct.

Collapse
ddekany profile image
ddekany

My point didn't go though. I wasn't talking about uncaught mistakes. My concern is about how self documenting the code will be, and for what was that sacrificed. Let me try again. If a type T has a set of functions associated that satisfy the I interface, and also they behave as described in the documentation of I, then most certainly the author of T (or of the functions) has deliberately "implemented" the I interface there. Right? I mean, just how often does such thing happen by chance? If almost never, then why do the Go designers want us to not state that intent (I'm implementing I) in the language? What's the actual, practical, every day use case for "implementing without stating it"? Surely it's not that Go developers often get extremely lucky and so can avoid adapters.