[erlang-questions] Re: How to reduce the repetitious code in create mnesia table?

Mazen Harake <>
Tue Mar 30 13:57:13 CEST 2010


On 30/03/2010 12:12, Magnus Henoch wrote:
> 钱晓明<>  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.
>    
I agree with Magnus but just wanted to add one thing: Rollback. If you 
would want to "revert" some data written somewhere (or tmp tables 
created) if something goes wrong then catching is a good thing.

This is why you *usually* do it like Magnus says (just let it crash) and 
sometimes catch it.

More here: 
http://mazenharake.wordpress.com/2009/09/14/let-it-crash-the-right-way/

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

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

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