[erlang-questions] Newbie question: avoiding massive 'case' statement
Richard Carlsson
richardc@REDACTED
Wed Mar 5 22:33:32 CET 2008
You can do something like this:
request_type("ZABC") -> zabc;
request_type("Z123") -> z123;
request_type("YPQX") -> ypqx;
...
request_type(String) -> throw({unknown_transaction_type, String}).
that maps identifier strings to module names, and then
M = request_type(TransactionTypeString),
Result = M:process_request(Request)
Since atoms are quicker to compare, you probably want to do the
string-to-atom mapping quite early. If you want to separate atoms that
identify request types from the actual handler module names, you could
use another function that performs id-as-atom-to-handler-module mapping:
M = request_handler(request_type(TransactionTypeString)),
...
/Richard
David Mitchell wrote:
> 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
>
> This is all fine and dandy, but I'm expecting the 'case' statement to
> grow to handle several hundred different values of TransactionType
> over time. The code is going to get unwieldy in size, and the
> likelihood of mistakes in cut/paste updating of the 'case' block is
> going to get pretty high.
>
> As an alternative to the above, is there a way to do something like
>
> try
> &&&TransactionType&&&:process_request(Request)
> catch
> error_logger:info_msg("Unknown transaction type")
> end
>
> where &&&TransactionType&&&:process_request(...) is some "magic code"
> that lets me call the process_request function in the module that has
> the name of the value of TransactionType (hopefully that's clear, if
> not necessarily English)?
>
> Alternately, is there some sort of refactoring I could do to avoid the
> massive 'case' statement?
>
> There may be some obvious solution to do this, but I haven't been able
> to find it...
>
> Thanks in advance
>
> Dave Mitchell
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
More information about the erlang-questions
mailing list