Re: [Hampshire] Code style

Top Page

Reply to this message
Author: Damian Brasher
Date:  
To: Hampshire LUG Discussion List
Subject: Re: [Hampshire] Code style
Hugo Mills wrote:
>    If you were writing a function with a fast path and a slow path,
> which style would you use to write the function?

>
>
> Style A:
>
> if can_use_fast_path:
>     return "fast path result"
> # do slow stuff
> return "slow path result"

>
>
> Style B:
>
> result = "fast path result"
> if !can_use_fast_path:
>     # do slow stuff
>     result = "slow path result"
> return result

>
>
>    Assume that the fast path is a single expression, and the slow path
> is at least tens of lines of code. Why would you pick one style over
> the other?  Would you use a different idiom in different languages? If
> so, why?

>


I have used both in different contexts but where Perl will return the value
of the last expression evaluated in a subroutine ensuring the exit point is
at the end of a subroutine could mean more readable/consistent code, so B.

For error handling style B offers a single test opportunity. Perhaps for
maintenance ease this is a better choice producing a more robust idiom. It
may be more difficult to keep track of the value of result when using style B
where the danger of this is minimal in A as the exit point occurs as soon as
result receives a true value, minimising the chance of an incorrect value
accidentally being assigned to result due to a copy and paste or similar
error.

I think in general a single exit point has benefits over two.

Damian

--
WWW http://www.diaser.org.uk - working together to make long term digital
archives more accessible

RSS http://sourceforge.net/export/rss2_projnews.php?group_id=258272


--
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.