On 5/11/07, Michael Chesterton <[EMAIL PROTECTED]> wrote:

Is there some sort of common practice about where to return from a function?
I've got this vague recollection of not returning from just anyway. ie

for(foo)
 if(test1)
  return false
 else if(test2)
  return false
return true

against

valid = true
for(foo)
 if(test1)
  valid = false
 else if(test2)
  valid = false
if(valid)
 return true
else
 return false


As a general rule each function should have a single return statement,
unless there's a good reason not to. Sometimes the structure of a
function is such that having a single return statement is impractical,
but in the case like the one given above I would write it as

valid = True
for foo:
   if test1 or test2:
       valid = False
       break
return valid

I find that a single return statement makes it easier to read,
refactor and debug code. Other people have have different preferences
for different reasons, but that's my 2c.

Cheers,

Tim

Same with exiting a program, I take it it's better to do something like

if(!foo())
 exit(1)

as apposed to exiting from within foo?
_______________________________________________
coders mailing list
[email protected]
http://lists.slug.org.au/listinfo/coders

_______________________________________________
coders mailing list
[email protected]
http://lists.slug.org.au/listinfo/coders

Reply via email to