When explicit "else" is necessary in control structures? - php

What should one use?
This, without else:
function($condition) {
if($condition) {
return true;
}
return false;
}
Or this, with an else:
function($condition) {
if($condition) {
return true;
} else {
return false;
}
}
What are potential drawbacks?
Note: I understand that right solution for this very example would be
function($condition) {
return (boolean)$condition;
}

I like this approach:
function($condition) {
$retValue = false;
if($condition) {
$retValue = true;
}
return $retValue;
}
This way you know where this function will return, (always at the end) which is good for later analyzing. You set a default value and only change it if the condition is right.

With else there is a better readability. However, both the functions are doing the same as the function is terminated by the return function. I find it also safer to use the else if in some cases you can forget using the return function which then go further to return the false.

I would use the else too, for these reasons:
Your code is better readable
In complex code, like when you use if/else within other if/else's, debugging will be much easier.

In some cases it is possible to increase readability by setting "else" aside. Two examples below are eqiuvalent. Second produces less code, though it will suit only when we return values without complex calculations in that block, but again, we can utilize functions to make it usable.
function($a, $b) {
if($a) {
if($a > $b) {
return true;
} else {
return false;
}
} else {
return false;
}
}
function($a, $b) {
if($a) {
if($a > $b) {
return true;
}
}
return false;
}
Note: if not speaking about general cases with more complex conditions assumption, this should fold to:
function($a, $b) {
return ($a and $a > $b);
}

In the first one both true and false will be returned, as when the if statement finishes, it will go and do the very next thing, return false. In the second one, one true OR false will be returned, depending on the condition. Draw backs for the first one would be that you get both true and false returned, which could confuse a function that's only asking for one parameter, and receiving two instead. This is assuming that you include this inside a larger function. I'm not sure why you would want to use the first one though. Hopefully this helps!

Related

Which is the better approach if I want my code to be efficient

I didn't go to school when I started learning to code. I read books and browse the web. And this question really didn't appear in any of the books I read. And if I search it online I don't know what to search so I apologize in advance if this is obvious to you because it isn't to me.
Anyway is this approach better if I want my code to be efficient:
if($a == $b && $a <= $c && strlen($a) > 100 && functionA($a) && functionC($c)){
//win
} else {
//fail
}
OR
is this better:
if($a != $b){
//fail
} elseif($a > $c) {
//fail
} elseif(strlen($a) < 100){
//fail
} elseif(!functionA($a)){
//fail
} elseif(!functionC($c)){
//fail
} else {
//win
}
In javascript, I see compilers mash code up and eliminate all white space as possible and change variable names to a single letter (e.g. thisname to a) etc. In my understanding they do it so that the size of the javascript file is so small that when the page asks for it, loading time wouldn't be a problem.
But how about for php files? Which of the code above is better if I want my code to be efficient? why? AND Does the javascript scenario apply to php? Thanks
As has been noted in the comments, efficiency is the least of your concerns here, readability and thereby maintainability are more important. Typically you'd use a fail early approach to achieve this:
function myTest($a, $b, $c) {
if ($a == $b) {
return false;
}
if ($c < 10) {
return false;
}
if (...) {
return false;
}
...
return true;
}
Alternatively you may want to be throwing specific exceptions or return specific error codes instead of merely returning false to signal exactly what was wrong.
I'd say readability is most important factor, you won't win any speed anyway - compilers are quite smart.
if (passesRequirements($a, $c)) {
//win
}
function passesRequirements($a, $b)
{
return isNotEqual($a, $b)
&& isLargerThan($a, $b)
&& isShorterThan($a, 100);
}
function isShorterThan($str, $amount)
{
return strlen($str) < $amount;
}
and so on.

returning from multiple points in a function

This is more or less a readability, maintainability and/or best practice type question.
I wanted to get the SO opinion on something. Is it bad practice to return from multiple points in a function? For example.
<?php
// $a is some object
$somereturnvariable = somefunction($a);
if ($somereturnvariable !== FALSE) {
// do something here like write to a file or something
}
function somefunction($a) {
if (isset($a->value)) {
if ($a->value > 2) {
return $a->value;
} else {
return FALSE;
} else {
// returning false because $a->value isn't set
return FALSE;
}
}
?>
or should it be something like:
<?php
// $a is some object
$somereturnvariable = somefunction($a);
if ($somereturnvariable !== false) {
// do something here like write to a file or something
}
function somefunction($a) {
if (isset($a->value)) {
if ($a->value > 2) {
return $a->value;
}
}
return FALSE
}
?>
As a matter of practice, I always try to return from ONE point in any function, which is usually the final point. I store it in a variable say $retVal and return it in the end of the function.It makes the code look more sane to me.
Having said that, there are circumstances where say, in your function as the first line you check if a var is null and if yes you are returning. In this case, there is no point in holdin on to that variable, then adding additional checks to skip all the function code to return that in the end.
So...in conclusion, both ways works. It always depends on what the situation is and what you are more comfortable with.

Nested if statements, any possible way of cleaning?

I have checked a few other questions but they don't really give me the answer I expect..
My code is a like this..
private function handle()
{
if()
{
if(!condition)
{
if(!condition)
{
if(!condition)
{
if(!condition))
{
if(!condition)
{
if(!condition)
{
if(!condition)
{
if(!condition)
{
if(!condition)
{
code
}
return;
}
return;
}
return;
}
return;
}
return;
}
return;
}
return;
}
return;
}
return;
}
}
In my opinion it is readable but messy, sadly I haven't found really a way of making it look 'pretty'. Any ideas?
EDIT: Each return is different.
EDIT2: Gave an answer of my own, thanks everybody!
Conditions can be merged by a && operator..It works form left to right, which means, as soon as the any one starting from left fails, it stops evaluating the condition..
if($a) {
if($b) {
}
}
can be replaced by
if($a && $b) {
}
Use a variable check, or combine the conditions into fewer IF statements.
Variable check like so:
$execute = TRUE;
// Opposite of what you want, e.g. if you want $a only to be TRUE, do $a !== TRUE
if (condition) {
$execute = FALSE;
}
...
// If all the conditions were met, then everything is OK
if($execute === TRUE) {
// code
}else {
// return
}
Edit:
Variable check can be preferably to combining IF statements if you want more control on what returns, e.g. something specific happens if a certain condition fails, which combining conditions can not always allow for.
Like already posted use
if(condition1&&condition2){}
or if this will not work, you can also use function which stops as soon as a condition is true
function some(){
if(!conditon 1){return 0;}
if(condition 2) {return 1;}
}
this provides more power as second if works only if first doesn't satisfy.
You must choose based on your requirements. Sometimes though nested loops are unavoidable.
I thought it out and have found a nice way of doing it, basically I'll make a method for each basic condition, and I'll call them in an if statement with the bitwise AND operator (&), which don't short-circuit.
/**
* nonsql_condition - It means it doesn't check with the database
*
* sql_condition - It means it does check with the database.
*/
if(!$this->nonsql_condition() & !$this->nonsql_condition() & !$this->nonsql_condition() & !$this->nonsql_condition())
{
if(!$this->sql_condition())
{
return error;
}
if(!$this->sql_condition())
{
return error;
}
code;
}
This allows me to use fewer lines of code in my method, plus also not doing unnecessary queries to my database.

function return code block query

Quick question to do with php functions, it may sound silly to some of you but I dont want to get in to bad habits. Is there anything wrong with doing the following?
function do_something($val)
{
$a = 1;
if ($val==$a)
{
return true;
}
return false;
}
Instead of;
function do_something($val)
{
$a = 1;
if ($val==$a)
{
return true;
}
else
{
return false;
}
}
Sorry guys I think my example isn't great. Basically the function could insert data into a database or send an email etc. With these functions I may only need to now whether it was successful or not by returning true or false. I wanted to know whether its suitable that I can use the shorter method instead of the if-else block.
I hope that makes it clearer.
Not really. Both works the same. However, it would be much cleaner to write it like this:
function do_something($val)
{
$a = 1;
return ($val==$a) ? true : false;
}
That's totally cool, because when returning a value, the function is left and it doesn't matter what follows.
But you could shorten this with
function do_something($val)
{
$a = 1;
return $val == $a; // this condition will be evaluated to true/false
}
The shortest way to do it:
function do_something($val)
{
return ($val==1) ;
}
No, that is perfectly fine, and in fact advised in multiple cases. :)

Using if...else... or just if... to determine what is returned

Which is better?
function test($val = 'a') {
if($val == 'a') {
return true;
}
return false;
}
or
function test($val = 'a') {
if($val == 'a') {
return true;
} else {
return false;
}
}
Effectively, they do the same thing. If $val isn't 'a', the function returns false. Just personal preference?
They are the same. However, for this case, I prefer:
function test($val = 'a') {
return ($val == 'a');
}
I think it comes down to how the comparison "feels" to you. I'd use the first if it seemed like $val being "a" was a special case, and usually the function returned false. I'd use the second if it felt more like it was 50/50 which way it would go.
Over those, I prefer the second for clarity. However, I actually prefer
return ($val == 'a');
In PHP, if nothing is done in a function and the end is reached it will be as if it returns false. Because of this it's never necessary to return false if nothing else is to be executed inside the function. This leaves us with this:
function test($val = 'a') {
if($val == 'a') {
return true;
}
}
If there is only one command after an if, elseif or else statement, the braces ("{" "}") aren't necessary, which make us end up with this:
function test($val = 'a') {
if($val == 'a') return true;
}
In PHP you can actually return a comparison, which will be executed right before it's returned. This is what some of the others who answered this post suggested. Doing this leave us with this code:
function test($val = 'a') {
return ($val == 'a');
}
True will be returned if the block "($val == 'a')" is true, otherwise false will be returned, since it's not true. Logic.
I actually tend to use the second convention I presented, just out of habit. Seeing the beauty of the simplicity of the third one presented by the others I will probably switch to that when applicable.
EDIT:
If you want to write code that is easier for non-PHP experts to understand, another alternative might be the following:
function test($val = 'a') {
if($val == 'a')
return true;
else
return false;
}
I'd say that not using the braces in the circumstances as described in my second example gives you easier-to-read code, since the braces tend to make your code look messy if they don't contain multiple rows.
I really believe it's what ever intent your trying to convey for the code. If you look at this:
function test($val = 'a') {
if($val !== 'a') {
return false;
}
return true;
}
You can see that it does the same thing as your examples, but it has a different intention. For this example it really wouldn't make any sense to have:
function test($val = 'a') {
if($val !== 'a') {
return false;
}
else {
return true;
}
}
I think that #Ned had it, because he is trying to convey an intention for the if operation.
If you were not returning boolean I would choose the first form. In this case, I would simply do :
return ($val == 'a');
as others have suggested.
I'd stick with the first one, the simpler the code (and easy to read) the better.
While you are reading second code block. You can easily understan that it returns false when val is not equal to 'a'.
But at the first code block it's a bit hard to understand when it'll return false. It's not so hard at that example but i assume that your if clauses won't be so simple.
Rather than:
function test($val = 'a') {
if($val == 'a') {
return true;
} else {
return false;
}
}
The below approach is better, there is no more overhead of else and code is also short:
function test($val = 'a') {
if($val == 'a') {
return true;
}
return false;
}
It could be made even shorter:
function test($val = 'a')
{
return ($val == 'a');
}

Categories