[erlang-questions] Simple multi-case

Richard A. O'Keefe ok@REDACTED
Tue Nov 14 00:22:18 CET 2006

I wrote:
    There is no such thing as code that is too small to move into a
    separate function.

"datacompboy" <datacompboy@REDACTED> replied:
	separate function -- more chars to type, and code far from table

More characters to type?
 (a) If it makes the code clearer, what the heck does THAT matter?
 (b) You can probably use machine aid.  For example, it should be a
     small matter to program Emacs or an Emacs-like editor (such as
     Alpha) so as to add an "extract function" command.  Select the
     expression you want to be the body, type some chord, and presto
     chango, there's a function.  (This kind of thing is apparently
     routine in Eclipse thse days.)
 (c) If the body of the function is so small that this is a problem,
     then it won't hurt to type it twice in the case expression; if
     it's big enough to be annoying to write twice in the case
     expression, you'll probably type *less* by making it a function.
 (d) Give a specific example and then we can discuss the issue without
     wandering off into generalities.

Code far from the table itself?
 (e) Certainly not!

     Common_Case = fun () -> ....  end,
     case Whatever
       of foo -> Common_Case()
        ; bar -> Common_Case()
        ; ugh -> uncommon_case()

     Apparently the Erlang compiler *doesn't* inline a local function
     like this, but it *could*, and arguably it should.  The main point
     is that the function *doesn't* have to be far from the case.
	separate function is not a problem to speed of runtime, but that
	problem for development speed.  I need at least create new function
	name, that must contain info about "what doing here", but not "how it
	doing that", since after some changes name will be wrong...


	Cascade CASEs better, than just copy code, and better than
	separate function for short results.  As for now, its my decision:)

Let me make another suggestion.  The difficulty you are encountering is
a typical "code smell", of the kind that should suggest a refactoring.
What kind of refactoring?  In this case:  a DATA refactoring.

Suppose you have

    type t() -> fee | fie | foe | fum

and you find yourself wanting to write

    case X
      of fee | fie -> boo()
       ; foe | fum -> jum()

Is this just an exceptional case?  If so, put up with writing the case
bodies twice.  If it's *not* an exceptional case; if you think you are
likely to need this again, that's a sign that you should have

    type t() -> {bee,(fee|fie)} | {fly,(foe|fum)}

and the case expression should be

    case X
      of {bee,_} -> boo()
       ; {fly,_} -> jum()

As I said above, let's see a real example.

More information about the erlang-questions mailing list