DEV Community

loading...

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

Collapse
thomaslevesque profile image
Thomas Levesque

Sounds like a really bad idea to me. What if a class has a method with the same name as an interface method, but with completely different semantics? If you want to use Salad as an Edible, just make an EdibleSaladAdapter, and you're done... Sure, that's more work; but at least it's safe.

Collapse
dean profile image
Dean Bassett Author

If you see that a method takes a Closer ("Closable" in other languages), sure a struct for a door might have a Close() method, but is it really a good idea to pass it to a method like io.CloseAndQuit(Closer)?

In Go, it's usually quite clear what interfaces are intended to be used for, so while it's possible to pass something like a door or a cabinet into an io function, it's pretty clear that you'll get unintended consequences. It might not be as safe in a few select contexts, but you get the huge benefit of convenience that I've described above.

Collapse
solitarycipher profile image
Nick

Haskell's approach is interesting as well, and not dissimilar from Go. In Haskell you can declare an interface (but really a typeclass), and then explicitly make a type "part" of that interface. It would be like declaring a class in Java, then declare interface, then you can define an implementation of the interface's method separate from the original class.

This has the benefit of not having to know which interfaces a type follows when you declare the type, as well as having to explicitly make a type to be a part of the interface.