[erlang-questions] Protocol Mapping
Steve Davis
steven.charles.davis@REDACTED
Wed Dec 19 13:50:02 CET 2012
Hi,
I'm frequently facing situations with binary protocol translations/transforms where I need to map binary codes to e.g. atoms and back.
This is of course "easy" in Erlang, but suffers some inconveniences. I've attached a code snippet distilled down to the simplest case to explain my issue.
I'm sure the first codec pattern below is familiar, and for sure is efficient.
However, there are multiple places where updating is required to add new message types.
The second pattern is much less usual, but handy as one line achieves the addition of a new message type.
It helps particularly when there is more than one pairing involved (e.g. {atom, code, status_message}).
For sure this cannot be something nobody has seen/thought about. I'm wondering if anyone has comment on this, and maybe suggestions for approaches that I haven't thought of.
/s
-------
-module(mapping).
-compile(export_all).
%% traditional
-define(HELLO, 100).
-define(HELP, 101).
-define(DONE, 102).
encode(hello) -> ?HELLO;
encode(help) -> ?HELP;
encode(done) -> ?DONE.
decode(?HELLO) -> hello;
decode(?HELP) -> help;
decode(?DONE) -> done.
%% alternative
-define(MAP, [
{hello, 100},
{help, 101},
{done, 102}
]).
encode0(X) ->
{X, Y} = lists:keyfind(X, 1, ?MAP),
Y.
decode0(X) ->
{Y, X} = lists:keyfind(X, 2, ?MAP),
Y.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20121219/13d96f8c/attachment.htm>
More information about the erlang-questions
mailing list