Dustin Oprea
Dustin Oprea

Reputation: 10236

Erlang Interface-Based Design

If I'm going to build new modules, but want to, first, define templates (interfaces/contracts) that they would have to satisfy, should I use behaviors, or is there some more-preferred solution? Obviously, I'd like to build my [non-trivial] modules in such a way that I can drop in different implementations of that functionality, later.

I want to make sure that I'm building proper and efficient habits, and searches aren't turning up immediate/useful information on the subject.

Thanks.

Upvotes: 1

Views: 213

Answers (2)

I GIVE CRAP ANSWERS
I GIVE CRAP ANSWERS

Reputation: 18869

In erlang, you can just let a module have the same methods with the same types and that is enough. If you want to make sure that a certain kind of specification and/or contract is there, you can use an R15 feature with behaviours and -callback to make a type specification which the dialyzer can check for you. Apart from that, the usual good ideas apply: regard values you obtain from your abstraction as abstract outside your module. Otherwise, simple drop-in replacement is not going to be as effective.

I often abstract in erlang by having an interface module. Say I am writing application foo. I often have a module foo and this module is the only way to use the application. You are not allowed to call into the application in any other way. For larger systems, there are more modules which are publicly exposed, but the basic idea is to keep the list of exposure small.

This ensures you can rewrite what is behind the factored module as you want. You can decide to add more processes, change the supervision tree and so on.

The key in Erlang is often to specify a protocol between processes. And keep that one stable. The protocol forces decoupling since processes cannot share state and this is to your benefit when you want to redesign parts of the code later.

Upvotes: 3

0xYUANTI
0xYUANTI

Reputation: 404

Behaviours are basically your only option :( I use them heavily for this purpose but would really love to have something more akin to ML functors instead.

For interfaces at less than module scale, there are higher order functions with type annotations, also suboptimal.

Upvotes: 1

Related Questions