If/else Vs. If Only When Using Return

What is the (semantic?) difference (if any) between using:


if(something)

	return true;

else

	return false;

versus:


if(something)

	return true;


return false;

Because (in this example situation) we’re using return as the only statement in each condition, I don’t see any difference between these two code bloks. But second one seems to be less readable for me.

or


return something;


return null !=== something;

Not necessary. I gave example with “if(something)” as… an example! :] Condition doesn’t always have to be boolean.

The same question goes for any kind of condition / check. What matters in my question, is that you always use return statement, which allows you to omit "else" part.

There’s no difference. But i agree, the first example is more clear. From a quick view you could miss the first return and thus think, that the function always returns false.

You can also use




if(something)

        $result = true;

else

        $result = false;

return $result;



or even this variant


return (bool) (something);

there is not much diff but first one is more clear

you can discuss which is more/less readable, but I would say something different:

for me it does not matter if you use ‘else’ or not, but you should always use curly brackets with if/for/do/while etc even if there is only one instruction. It is much more clear and prevent hard to trace errors when you add second instruction and forget to add brackets then :)

Using brackets makes both examples clear enough for me:




if(something) {

        return true;

} else {

        return false;

}






if(something) {

        return true;

}

return false;



because in both cases you can clearly see which part belongs to ‘if’, which to ‘else’ and where whole ‘if’ or ‘if…else’ block ends.

just good practice which Java IDE editors even report as ‘notice’ and encourage you to correct it :)

Then, it is even more painfull for me, that I found second example (agreed by most as less readable) in Yii core! :]

[color="#1C2837"][size=“2”]Not necessary. Because, as I wrote in an answer to alex-w, I just gave this example with “if(something)”. Condition doesn’t always have to be boolean. And if it is not, then your examples will fail.[/size][/color]

[color="#1C2837"][size="2"]But thank you for contribution.[/size][/color]

For me this is a phundament of coding! :]

I only omit currly braces, if I put statement in the same line as if:


if($something == 5) SomeClass::callFive();

So I totally agree with you that using curly braces should be mandatory in most cases.