How to reduce the repetitious code in create mnesia table?

Magnus Henoch <>
Tue Mar 30 12:12:44 CEST 2010


钱晓明 <> writes:

> Is there any way I can do to reduce the repetitious code? I have
> tried defining a new function accepting the name of record to do the same
> thing above, but can not compile code because of record_info.

You could do it with a macro.  Something like:

-define(CHECK_CREATE_TABLE(Name, Attrs),
        case mnesia:create_table(Name, [{attributes, record_info(fields, Name)}|Attrs]) of
            {atomic, ok} -> ok;
            {aborted, {already_exists, Name}} -> ok
        end).

It's used like this:

    ?CHECK_CREATE_TABLE(user, [{disc_copies, DiscCopies}]),

> By the way, I do not find the way to leave a function except using
> throw/exit. Is there any way I can use to just leave current function,
> replace the "throw" statement above?

First of all, I'd suggest using erlang:error instead of throw.  In my
mind, "throw" is for flow control within a small set of related
functions, while "erlang:error" is for error messages to whoever is
listening.  (Usually the supervisor and the error logger.)

Back to your question.  Mazen already explained how you can do this.
I'll try to explain why you usually don't want to do it :)

Failure to create a table is probably something that the calling
function can't do anything about, so if the table creating function
returns {error, something}, the calling function would have to detect
that and return the same, and so on along the call stack until you reach
a function that can do something about it - but then you've duplicated
the functionality of Erlang errors _and_ supervisors.  More often than
not, you get what you want for free if you just signal errors and let
the code crash.

-- 
Magnus Henoch, 
Erlang Solutions
http://www.erlang-solutions.com/
---------------------------------------------------

---------------------------------------------------

WE'VE CHANGED NAMES!

Since January 1st 2010 Erlang Training and Consulting Ltd. has become ERLANG SOLUTIONS LTD.

www.erlang-solutions.com



More information about the erlang-questions mailing list