Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit a function in case condition is not satisfied

What is the best way of writing code to exit a function in case condition is not satisfied?

e.g I have a function

-(IBAction) moreDetails
{  
if (condition)  
//condition not satisfied...exit function  
else  
continue with the function 
}

Can i simply write return ?

like image 540
copenndthagen Avatar asked Feb 13 '11 18:02

copenndthagen


2 Answers

Yes. "return" returns immediately from the current method/function. If the function/method returns a value then you need to provide a return value: "return NO, return 3, return @"string", and so on.

I generally prefer this structure:

void f()
{
    if ( ! conditionCheck )
        return;
    // long code block
}

to this:

void f()
{
    if ( conditionCheck )
    {
        // long code block
    }
}

because fewer lines are indented

like image 193
Bogatyr Avatar answered Oct 12 '22 13:10

Bogatyr


Yes - you should use return. Because your method returns void, no need for anything else. I'd write more, but there's not much else to it :)

like image 42
lxt Avatar answered Oct 12 '22 13:10

lxt