What alternatives are there to parameterised modul

2019-04-11 17:32发布

问题:

I can see why parameterised modules are used so much, as they allow us to do things like:

X = y:new("param").

X:action1().
X.get_property():

: which feels very OO. However, this is only an experimental feature in Erlang and I hear it may be removed, so I need to find an alternative.

回答1:

Parametrised modules are nothing but a shortcut on the first argument of a function. See these two examples:

-module(y, [Name,Age]).
-compile(export_all).

action1() -> io:format("Hello, ~p!~n",[Name]).

get_age() -> Age.

Run it:

1> c(y).
{ok,y}
2> X = y:new("Fred",22).
{y,"Fred",22}
3> X:action1().
Hello, "Fred"!
ok
4> X:get_age().
22

Now without parametrized stuff:

-module(y).
-compile(export_all).

action1([Name,_]) -> io:format("Hello, ~p!~n",[Name]).

get_age([_,Age]) -> Age.

Running it:

1> c(y).
{ok,y}
2> X = ["Fred",22].
["Fred",22]
3> y:action1(X).
Hello, "Fred"!
ok
4> y:get_age(X).
22

The biggest 'advantage' of parametrized modules is that you shift the burden of carrying state from a variable to a module name. This is in appearance much simpler to someone not used to 'the Erlang way', but it clashes with conventional styles of code.

It's not just a question of being experimental or not. You throw out referential transparency and the semantics to immutable variables become a bit weird. A good example of this is to imagine you add the following functions to a parametrized module:

ret_fn() -> fun(Age) -> Age + 5 end.

When compiling the module, you get the warning ./y.erl:8: Warning: variable 'Age' shadowed in 'fun'. This is warning you that you are using the name of a predefined variable within the head clause of an anonymous function. However, a quick look at the ret_fn/0 function shows absolutely NO sign of where that variable is from.

Now imagine that you use the variable Name for any other purpose; you will get a run time error telling you ** error: no match of right hand side value < ... >.

The point I'm making is that parametrized modules reduce the amount of typing you need to do at the expense of logical simplicity. Not just for you, but for any other Erlang programmer to work on your code.

On top of that, tools like dialyzer, TypEr, tidiers and whatnot have no guarantee to support these idioms. These tools are pretty useful, too! Don't dismiss them. (Edit: newer versions of Erlang (R13B04+) now guarantee that support)

The best alternative to parametrized modules is to avoid them and use what every other Erlang programmer outside of mochiweb is using.



回答2:

Why can't you use the usual way i.e. send message to a (registered) server process associated with a module?

The message in question can be whatever you want of course e.g. configuration etc.

What problem are you trying to solve that can't be handled in such way?



标签: erlang