Question

In a language where it is possible to define interfaces and typedefs (using Dart here):

abstract class Receiver {
  void receive(int quantity);
}

typedef void Receive(int quantity);

abstract class Transport {
  void deliver(Receiver receiver);
  void deliver(Receive receive);
}

Conceptually, are single method interface and type definition on functions the same thing? Is there any benefits from using one over the other?

Était-ce utile?

La solution

Single method interfaces and functions (or functions type definitions) are almost the same. Function type definitions are just anonymous interfaces. Interfaces and function type definitions both serve the same purpose. And together with their implementation they could be described as mathematical duals. An object (or in this case a single method interface with implemention) is data (state) with behavior and a function is behavior with data, called a closure when data is partially applied. In C# e.g. the compiled IL code is similar in both cases (at least when it is reverse engineered). This and the correspondence to the concept of duals is described by Mark Seemann here. Note that this holds for C# and might be different in other languages or with other compilers.

In object oriented languages the intent of interfaces is to decouple the code and to be able to inverse the control (as in IoC). This gives you lots of benefits like reduced dependencies and therefore maintainability, evolvability, testability etc. In functional programming the same thing is achieved by using functions type definitions. In some languages you can do both.

Major differences is that interfaces are a bit more verbose with some boiler plate code. Functions are more concise. I'm not sure if all IoC Containers can handle functions as parameters. Also and even more important the way of programming might become very different when you go for one or the other depending on the context. If it's not convenient (meaning not idiomatic) in the language to use type definitions e.g. it can make things complicated when working in a team. So a good advice is probably to check the language's coding guide lines and conventions. (I don't know Dart so I can't help you here.)

Autres conseils

Conceptually, are single method interface and type definition on functions the same thing?

No.

In most languages that allow both, the function typedef defines a type whose values are functions and nothing else. The abstract class defines an interface which has a function (and likely, other things).

Things can get muddled with closures (which are functions, but often have other things) and/or C++ style functors (classes that have operator() overloaded), or even with implicit conversions to function types.

But the two mechanisms serve different purposes and should be conceptually different, even if mechanically they can be made to do the same things.

Licencié sous: CC-BY-SA avec attribution
scroll top