[erlang-questions] Newbie question: avoiding massive 'case' statement

Ulf Wiger (TN/EAB) ulf.wiger@REDACTED
Wed Mar 5 22:27:31 CET 2008


David Mitchell skrev:
> Hello everyone,
> 
> Newbie alert...
> 
> I've got a block of code that looks like:
> 
> case TransactionType of
>   "ZABC" ->
>     zabc:process_request(Request);
>   "Z123" ->
>     z123:process_request(Request);
>   "YPQX" ->
>     ypqx:process_request(Request);
> ...
>   TransactionType ->
>     error_logger:info_msg("Unknown transaction type")
> end

If this is indicative of a pattern, then you could
try something like:

M = list_to_existing_atom(string:to_lower(TransactionType)),
M:process_request(Request).

For some added safety, you could do something like

case erlang:function_exported(M,process_request,1) of
     true -> M:process_request(Request);
     false ->
         %% Complication: M might not be loaded yet...
         error_logger:info_msg("Unknown transaction type")
end.


You can of course embellish the above to your liking.

BR,
Ulf W



More information about the erlang-questions mailing list