Small poll

Chris Pressey cpressey@REDACTED
Wed Dec 17 19:25:55 CET 2003


On Wed, 17 Dec 2003 10:09:05 +0100
Bengt Kleberg <Bengt.Kleberg@REDACTED> wrote:

> yes, i think i understand. you are saying that some code should be ok
> to compile, even if it will always crash at run time.
> would it seem very strange if i did not agree? because i do not, even 
> though i have not ever written a compiler. perhaps this is why?

Bengt,

I could be wrong, but I think it is more likely that it's because you
aren't used to writing Erlang code in the "let it crash" style.

In this style, you write code very aggressively.  You might have a
function like (this is just an example, not meant to do anything
useful:)

  foo(Bar) ->
    ok = file:setcwd(moo(Bar)),
    {ok, File} = file:open(zoo(Bar)),
    {ok, Records} = read_records(File),
    ok = file:close(File),
    Records.

So, the intent of the function is clearly to fail outright with
'badmatch' if anything goes wrong.  foo/1's callers presumably wrap
their calls to foo (or their calls to whatever eventually calls foo) in
a catch.  (Or the process that calls foo/1 is spawned, with the spawning
process linked/monitoring/trapping errors...)

The point is that foo/1 can fail, but that it's not *fatal*, in the
sense that the program keeps running.

Now what if we want a flag that disables this function?  Maybe
eventually we'll read the flag from a file, but for testing purposes,
we'll just define it as a constant in the source:

  baz_mode() -> true.

  foo(Bar) ->
    false = baz_mode(),
    ok = file:setcwd(moo(Bar)), [...] Records.

Just as clearly as the previous example I hope, the intent of that line
of code is to disable the function if we are in baz mode, not to stop
the program from being compilable if we are in baz mode! :)

Where "let it crash" style is supported in Erlang, it's not always
graceful ('try' may improve that, if it ever gets added,) but it usually
results in much clearer code, because the assumptions/assertions are
made explicit.

But even if you don't use it, you have to recognize that many
programmers do, and for the "let it crash" style to work, code has to be
allowed to crash at runtime, even when it "can't be right".

-Chris



More information about the erlang-questions mailing list