[erlang-questions] An Erlang 101 question

Garrett Smith g@REDACTED
Thu Jul 16 23:37:59 CEST 2015


Hey, I'm all for a direct solution, but this opening and closing of
the db for each read feels a little cavalier, even for me ;)

I would use a gen_server (e2 service) to maintain the open db,
flushing on each write to guard against data loss if the VM is
shutdown abruptly.

But to answer your question, a more canonical interface here would be
to return either {ok, Contact} or error (mapped from [Contact] or []
respectively) - or just return Contact and generate an exception if
the contact doesn't exists. The form depends on what you want this
function to do. See dict for an example of an interface that provide
both interfaces - and lets the user decide.

You're right though, exposing the dets interface here is wrong,
morally speaking.

On Thu, Jul 16, 2015 at 2:02 PM,  <lloyd@REDACTED> wrote:
> Hello,
>
> I have several functions that look like this:
>
> get_contact(Email) ->
>   open_db(),
>   Result = dets:lookup(?contacts, Email),
>   close_db(),
>   Result.
>
> The implication is that the function returns and empty list, [], if it fails to find a record, otherwise it returns a list containing the record.
>
> This makes it easy to distinguish the failure-to-return a record condition, but means that every function that depends up on get_contact/1 needs to do so and know what to do in that case. But that begins to feel like defensive programming.
>
> I can see several ways of dealing with this problem, but it occurs to me that there must be a conventional approach. What might be... what?
>
> Thanks,
>
> LRP
>
>
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions



More information about the erlang-questions mailing list