Defensive programming

Tony Rogvall tony@REDACTED
Wed Mar 29 08:07:16 CEST 2006


On 29 mar 2006, at 00.36, Pupeno wrote:

> Hello,
> I am used to defensive programming and it's hard for me to program  
> otherwise.
> Today I've found this piece of code I wrote some months ago:
>
> acceptor(tcp, Module, LSocket) ->
>     case gen_tcp:accept(LSocket) of
>         {ok, Socket} ->
>             case Module:start() of
>                 {ok, Pid} ->
>                     ok = gen_tcp:controlling_process(Socket, Pid),
>                     gen_server:cast(Pid, {connected, Socket}),
>                     acceptor(tcp, Module, LSocket);
>                 {error, Error} ->
>                     {stop, {Module, LSocket, Error}}
>             end;
> 	{error, Reason} ->
> 	    {stop, {Module, LSocket, Reason}}
>     end;
>
> is that too defensive ? should I write it this way


I suggest you think about the term {error,Reason} as any other term.
Either you need to handle it as a result from a function call, or you  
do not.


>
> acceptor(tcp, Module, LSocket) ->
>     {ok, Socket} = case gen_tcp:accept(LSocket),
>     {ok, Pid} = Module:start()
>     ok = gen_tcp:controlling_process(Socket, Pid),
>     gen_server:cast(Pid, {connected, Socket}),
>     acceptor(tcp, Module, LSocket);
>

The may be some reasons why accpet fail.

- The listen socket has closed.
- Resource problems.
- Timeout (if used)

This may require special treat.

/Tony





More information about the erlang-questions mailing list