How do interfaces differ between Java, C#, Go and Python, and what does that mean for the way you design?
Java and C# have interfaces that are almost the same, Go has interfaces that are filled in implicitly, and Python has duck typing where you do not declare anything at all. And the difference changes how you design.
public class Main {
public static void main(String[] args) {
Notifier n = new ConsoleNotifier();
System.out.println(n.notify("hello"));
}
}
And here is the Java version, where the class has to say that it implements the interface.
public interface Notifier {
String notify(String message);
}
public class ConsoleNotifier implements Notifier {
@Override
public String notify(String message) {
return "console: " + message;
}
}
And the four languages side by side.
the language how it works the style
-------------- ---------------------------------- ------------------
Java the class says implements nominal, explicit
C# the class says implements nominal, explicit
Go the method set has to match structural, implicit
Python nothing has to be said duck typing
And the Go version is the interesting one, because there is no interface keyword at all. An interface is just a list of methods, and any type with those methods satisfies it.
// This is what the Go version looks like.
type Notifier interface {
Notify(message string) string
}
type ConsoleNotifier struct{}
func (c ConsoleNotifier) Notify(message string) string {
return "console: " + message
}
And the Python version is even looser. There is no interface, so any object with the right method works.
class ConsoleNotifier:
def notify(self, message):
return "console: " + message
# Any object with a notify method works here.
def send(notifier, message):
return notifier.notify(message)
And what does that mean for the way you design? Here are the three practical differences.
the difference Java and C# Go and Python
------------------------ ------------------------ ------------------------
you have to declare it yes no
a type that has the no, it has to implement yes, it just matches
methods is enough the interface
a missing method is a compile error a run time error
found
And the third row is the one that changes the cost of a mistake. In Java, if you forget a method then the code does not compile, so the mistake costs you nothing. In Python the code compiles and then fails when it is called, so the mistake costs you a bug in production.
And the second row is the one that changes the design. In Java an interface is a contract that somebody owns and that the implementer agrees to. In Go the interface is owned by the consumer and the producer does not know about it at all.
So the rule to remember is this. Java needs the declaration, Go and Python do not, and that is why the same design looks different in each one.
The last question in this topic is about nominal typing.