[erlang-questions] case statements really required??

Attila Rajmund Nohl <>
Fri Dec 4 13:52:20 CET 2009


2009/12/4, kiran <>:
> hi,
> is it good to use case statements in functional language..  according to
> me .. pattern matching-functions could do the task.
> any commnets??

Using pattern matching leads to "function fragmentation", i.e. to
loads of one liner function cases and it gets hard to follow the
control flow. Let's consider this code:

check_language(Module) ->
    case catch Module:module_info(exports) of
	{'EXIT', _Reason} ->
	    not_blm;
	Exports ->
	    case {lists:member({blm_cmd, 0}, Exports),
		  lists:member({blm_error, 1}, Exports)} of
		{true, true} ->
		    {ok, blm_lang};
		_ ->
		    not_blm
	    end
    end.

12 lines, does what it's named (returns {ok, blm_lang} if the two
specified functions are exported from the module, otherwise returns
not_blm. Without case the code would look like this:

check_language(Module) ->
   really_check_language(catch Module:module_info(exports)).

really_check_language({'Exit', _Reason}) ->
  not_blm;

really_check_language(Exports) ->
  check_exported_functions(
    lists:member({blm_cmd,0},Exports),
    lists:member({blm_error, 1}, Exports));

check_exported_functions(true, true) ->
  {ok, blm_lang};

check_exported_functions(_, _) ->
  not_blm.

16 lines of screen used (and no documentation comments, type
specifications, etc. are written, they could add a couple of more
lines), a stupid function name had to be invented, etc. Consider the
equivalent in Java:

    String checkLanguage(String module) {
        try {
            int f=0;
            for (Method m : Class.forName(module).getMethods()) {
                if (m.getName().equals("blm_cmd") ||
m.getName().equals("blm_error")) {
                  f++;
                }
            }
            return (f==2?"{ok, blm_lang}":"not_blm");
        }
        catch (ClassNotFoundException e) {
            return "not_blm";
        }
    }

15 lines, but 5 of them contain only "}" (the original Erlang also
contained two lines of only "end", so it's the same length).


More information about the erlang-questions mailing list