3 ms·
In Java, you can run into situations where two classes share a method, but because they don't implement a common interface, for instance because they're part of
by isbadawi 14y ago
In Java, you can run into situations where two classes share a method, but because they don't implement a common interface, for instance because they're part of two different libraries, you can't e.g. write a method that accepts instances of either. You can't straightforwardly take advantage of polymorphism.
In Go this is never an issue; you can declare an interface that captures the methods you're interested in, and the existing code automatically implements it. It's kind of like duck typing in python (e.g. this function will work on any object that has a method <x>), except it's statically typed.
- pjmlp 14y agoJust because the method complies to the interface does not mean it does what you would expect from it. static fulfilment != semantic fulfilment.
- msbarnett 14y agoYou could equally say that just because a class declares that it "implements" an interface, it doesn't mean it does what you would expect from it. In practice, there is no language that can save you from people with malicious intent to confuse you. In practice, this is rarely an issue.
- pjmlp 14y agoThere is a big difference. When a developer makes a class implement an interface s/he signing a contract thus validating assumptions. When a type in Go matches an interface, it happens by chance.
- msbarnett 14y agoUtter nonsense. Either a function/method is semantically compatible with the expectations of its caller, or it is not. Whether or not the function/method's author typed the words "implements Foo" has absolutely no impact on this.