Best practice on ending if...else statement without else condition - php

What is the best practice to end an if...else statement without an else condition? Consider the following code:
$direction = $_POST['direction']; //Up or down
if ($direction == "up") {
code goes here...
}
elseif ($direction == "down") {
code goes here...
}
else {
//do nothing?
}
As you can see, there's only 2 condition; either up or down and the else statement doesn't really have a purpose unless you want it to display an error message.
Most of the time I see programmers simply put the else condition there but inserts a comment instead of any working code like this.
else {
//error messages goes here...
}
or just assume if it's not 'up' then everything else should be 'down' since there's only 2 condition. If a user inputs 'left' or 'right', it would still be considered as 'down'. I think this is somewhat inappropriate.
if ($direction == 'up') {
code goes here...
}
else {
code goes here...
}
I know that PHP would still work if we put if without else condition. But what if there is an elseif condition? In cases like these, what is the best practice if we want to maintain a strict if...else statement if we do not want to include any error messages or have any else conditions?
Thanks in advance.

There is no if...else statement.
There is only an if statement that can be extended with else and elseif operators.
So, the best practice on if statement without else condition is an if statement without an else condition:
if (condition) {
//some code
}
Frankly, there is no best practice. The best practice is just one that follows the program logic.
That's all

Don't write empty elses. This would just clutter up the code, and it's perfectly obvious what you meant.
In many cases, you can actually use the switch statement:
switch ($_POST['direction') {
case 'up':
// code ...
break;
case 'down':
// code ...
break;
default: // else
throw new Exception('Invalid direction value');
}

I think that if there's nothing to do on else, then there's no need for else block to exist in code. If else block is included, it means that it has a purpose to be there, so the code is incomplete yet, if it is empty.

This isn't something that can take a definite answer. Here's my take, it would be interesting to see what other opinions exist.
Scenario 1: Testing a boolean condition
This is the simplest case:
if (condition) {}
else {}
Specifying a condition as else if would be redundant, and it's really obvious to the reader what the code does. There is no argument for using else if in this case.
Scenario 2: Testing for a subset of infinite states
Here we are interested in testing for conditions A and B (and so on), and we may or may not be interested in what happens if none of them holds:
if (conditionA) {}
else if (conditionB) {}
else {} // this might be missing
The important point here is that there isn't a finite number of mutually-exclusive states, for example: conditionA might be $num % 2 == 0 and conditionB might be $num % 3 == 0.
I think it's natural and desirable to use a reasonable amount of branches here; if the branches become too many this might be an indication that some judicious use of OO design would result in great maintainability improvements.
Scenario 3: Testing for a subset of finite states
This is the middle ground between the first two cases: the number of states is finite but more than two. Testing for the values of an enum-like type is the archetypal example:
if ($var == CONSTANT_FOO) {}
else if ($var == CONSTANT_BAR) {} // either this,
else {} // or this might be missing
In such cases using a switch is probably better because it immediately communicates to the reader that the number of states is finite and gives a strong hint as to where a list of all possible states might be found (in this example, constants starting with CONSTANT_). My personal criteria is the number of states I 'm testing against: if it's only one (no else if) I 'll use an if; otherwise, a switch. In any case, I won't write an else if in this scenario.
Adding else as an empty catch-errors block
This is directly related to scenario #2 above. Unless the possible states are finite and known at compile time, you can't say that "in any other case" means that an error occurred. Seeing as in scenario #2 a switch would feel more natural, I feel that using else this way has a bad code smell.
Use a switch with a default branch instead. It will communicate your intent much more clearly:
switch($direction) {
case 'up': break;
case 'down': break;
default: // put error handling here if you want
}
This might be a bit more verbose, but it's clear to the reader how the code is expected to function. In my opinion, an empty else block would look unnatural and puzzling here.

I sometimes do it like this. I'm not worried that "left"
is interpreted as "down" because I always validate my input, in this case with preg_match('{^up|down$}', $direction). Inarguably a switch is more appropriate... but I dislike the verbose syntax.
if ($direction == "up")
{
// code goes here...
}
else //if ($direction == "down")
{
// code goes here...
}

I try not to write else. Ever. In my experience, using else results in less readable logic, especially when if/elses are being nested.
For assigning a var to either true or false (or any other simple this-or-that value), I always use:
$varx = false;
if ($my_codition_here === true) {
$varx = true;
}
When I have a bigger chunk of logic that you might consider "belongs" in the if/else, I make sure to structure my code so that if the condition is met, the function terminates, usually by returning:
if ($my_codition_here === true) {
// A reasonable amount of logic goes here
return $the_result_up_untill_here;
}
// All logic that would have been "else" goes here.
return $the_result_up_untill_here;
As phihag mentioned; use a switch statement when you consider elseif.
And as Your Common Sense already said, there is no best practise, but there are good practises, and I think this is one.

Related

Flow and logic - always testing for direct condition desired. !(!n) != n

Sorry in advance, I just don't know how to word this question nor look for it.
I feel like there should be a name for it, some sort of Principle, or Problem, but I don't know it. My title probably doesn't make sense either but I hope it will give enough of a hint.
I want to decide on a way to structure my code for a project. Specifically, nested conditions. In cases where you can't smack them together using AND, etc.
sell_insurance($person): bool {
if ($person->healthy() === true) {
if ($person->rich() === true) {
print 'sold!';
return true;
}
print 'not enough money';
return false;
}
print 'too risky to sell';
return false;
}
Versus:
sell_insurance($person): bool {
if ($person->healthy() !== true) {
print 'too risky';
return false;
}
if ($person->rich() !== true) {
print 'too poor';
return false;
}
print 'sold!';
return true;
}
I think the latter is easier to read, and if there was going to be like 50 nested ifs it would be just ugly. But, I want to make sure I will not run into issues down the line. Something unexpected I won't see from here.
These tests are simple. One thing I'm afraid of, is that not(not a) doesn't necessarily equal a. Sometimes we might expect logic to be boolean when in fact it might not be. I might test person->healthy() !== false, but I might not realize that instead of being true, it might be a string 'almost'. Or something less stupid.
My other concern, is, how to put this? The latter structure defaults to true. It feels less secure than the first approach.
Question to someone with more experience - what are up/downsides to the each approach? Which structure do you stick to, or do you shuffle them around? Thanks
I am learning PHP but I suppose this more or less applies to any language.
In those kind of situation several approuches are possible two of them are:
Using a switch statement to make everything more compact and readable.
But, as Kolos pointed out, it depends on your priorities and general scenarios...
You can even get rid of the logic operators, sometimes I use something like this below, to arrive to simple comparison statements:
$var= $person->healthy() ? 'true' : 'false';
$var.=$person->rich() ? 'true' : 'false';
switch ($var) {
case "truetrue":
echo "SOLD!";
break;
case "falsetrue":
echo "too risky to sell";
break;
case "truefalse":
echo "too poor!";
break;
default:
echo "NO WAY!";
}
Another commonly used is the usage of one or more so-colled guard clauses at the start that covers "corner cases".
In your exemple being rich AND healthy is mandatory, so let's put this as guard clause:
if ($person->healthy() && $person->rich()) {
print "SOLD!";
return true;
} elseif($person->healthy()) {
print "too poor...";
return false;
} elseif($person->rich()) {
print "too risky...";
return false;
} else {
print "NO WAY!";
return false;
}
You could also look at this an other way, either the person is accepted or declined, what makes his request declined could all be shown for example:
if the person is poor and not healthy, you will only "see" that he is not healthy since you returned before checking that.
It all depends on what you want as a priority not only structure wise.
The first approach indicates, that you HAVE to be healthy to get this item,
on the other hand the second one just adds some logic to it (this might not make sense)
If there were way more statements it would all depend on the priority, if you would return from each of them I would take the Second way, but it all depends on what makes more sense, what is easier to understand.

Best practice for returning in PHP function/method

I am refactoring an extensive codebase overtime. In the long run we are going to develop the whole system in classes but in the mean time I am using the opportunity to refine my PHP skills and improve some of the legacy code we use across several hundred websites.
I have read conflicting articles over time about how best to return data from a custom function, generally the debate falls into two categories, those concerned about best technical practice and those concerned about ease of reading and presentation.
I am interesting in opinions (with elaboration) on what you consider best practice when returning from a custom PHP function.
I am undecided as to which of the following as a better standard to follow using this basic theoretical function for example;
Approach a.
Populating a return variable and returning it at the end of the function:
<?php
function theoreticalFunction( $var )
{
$return = '';
if( $something > $somethingelse ){
$return = true;
}else{
$return = false;
}
return $return;
}
?>
Approach b.
Returning at each endpoint:
<?php
function theoreticalFunction( $var )
{
if( $something > $somethingelse ){
return true;
}else{
return false;
}
}
?>
A possible duplicate could have been What is the PHP best practice for using functions that return true or false? however this is not limited to simply true or false despite my basic example above.
I have looked through the PSR guidelines but didn't see anything (but I may have missed it so please feel free to point me to PSR with reference :) ).
Extending the original question:
Is the method used to return different depending on the expected/desired output type?
Does this method change depending on the use of procedural or object oriented programming methods? As this question shows, object orientation brings in its own eccentricities to further extend the possible formatting/presentation options Best practices for returns methods in PHP
Please try to be clear in your explanations, I am interested in WHY you choose your preferred method and what, if anything, made you choose it over another method.
I tend towards early returns - leave the function as soon as you know what is going on. One type of this use if called a 'Guard Clause'
Other things I will often do include dropping final else for a default:
if ($something > $somethingelse) {
return true;
}
return false;
and in fact, conditions of the form if (boolean) return true; else return false, can be shortened even further (if it is clearer to you) to just return ($something > $somethingelse);. Extracting a complex if clause from code like this to a usefully named function can help clear up the meaning of code a lot.
There are people arguing for single exit points in functions (only one return at the end), and others that argue for fail/return early. It's simply a matter of opinion and readability/comprehensibility on a case-by-case basis. There is hardly any objective technical answer.
The reality is that it's simply not something that can be prescribed dogmatically. Some algorithms are better expressed as A and others work better as B.
In your specific case neither is "best"; your code should be written as:
return $something > $somethingelse;
That would hopefully serve as example that there's simply no such thing as a generally applicable rule.
I know this question is old but the it is interesting and according to me
there are many things to say about it.
The first thing to say is that there is no real standard about returning in functions or methods.
It's usually ruled by the rules your team has decided to follow, but if you are the only one on this refactoring you can do what you think better.
In the case of returning a value the important thing I guess is
readability. Sometimes it's better to loose a little bit
of performance for a code that is more readable and maintainable.
I will try to show some examples with pros and cons.
Approach A
<?php
function getTariableType($var = null)
{
if (null === $var) {
return 0;
} elseif (is_string($var)) {
return 1;
} else {
return -1;
}
}
Pros:
Explicitness. Each case explains itself, even without any comments.
Structure. There is a branch for each case, every case is delimited clearly
and it's easy to add a statement for a new case.
Cons:
Readability. All these if..else with brackets make the code hard to read and
we really have to pay attention to every part to understand.
Not required code. The last else statement is not required and the code would be
easier to read if the return -1 was only the last statement of the function,
outside of any else.
Approach B
<?php
function isTheVariableNull($var)
{
return (null === $var);
}
Pros:
Readability. The code is easy to read and understand, at the first look we
know that the function is checking whether the variable is null.
Conciseness. There is only one statement and in this case it's fine and clear.
Cons:
Limit. This notation is limited to really little funtions. Using this notation
or even ternary operator becomes harder to understand in more complicated
functions.
Approach C.1
<?php
function doingSomethingIfNotNullAndPositive($var)
{
if (null !== $var) {
if (0 < $var) {
//Doing something
} else {
return 0;
}
} else {
return -1;
}
}
Pros:
Explicitness. Each case is explicit we can reconstruct the logic of the
function when reading it.
Cons:
Readability. When adding many if..else statements the code is really less
readable. The code is then indented many times looks dirty. Imagine the code
with six nested if.
Difficulty to add code. Because the logic seems complex (even if it is not),
it's difficult to add code or logic into the function.
Plenty of logic. If you have many if..else nested it is perhaps because you
should create a second function. NetBeans IDE for example suggests you to create
an other function that handles the logic of all your nested blocks. A function
should be atomic, it should do only one thing. If it does too much work, has
too much logic, it's hard to maintain and understand. Creating an other function
may be a good option.
Approach C.2
This approch aims to present an alternative to the C.1 notation.
<?php
function doingSomethingIfNotNullAndPositive($var)
{
if (null === $var) {
return -1;
} elseif (0 >= $var) {
return 0;
}
//Doing something
}
Pros:
Readability. This notation is very readable. It's
easy to understand what result we will get according to a given value.
Explicitness. As C.1, this approach is explicit in every branch of the
condition.
Cons:
Difficulty to add logic. If the function becomes a bit more complicated,
adding logic would be difficult because we may need to move all the branches of the
condition.
Approach D
<?php
function kindOfStrlen($var)
{
$return = -1;
if (is_string($var)) {
$return = strlen($var);
}
return $return;
}
Pros:
Default value. In this structure we can see that the default value is handled
from the beginning. We have logic in our function, but if we enter in no
branch we have a value anyway.
Ease to add logic. If we need to add a branch if it's easy and it does not
change the structure of the function.
Const:
Not required variable. In this case the $return variable is not required, we
would write the same function without using it. The solution would be to
return -1 at the end, and return strlen($var) in the if, and it would not
be less readable.
Conclusion
I have not listed all the possible notation here, only some of them. What we can
think about them is there is no perfect one, but in some cases an approach seems
better that an other. For example an is_null function would be fine with the
approach B.
Using an approach or an other is really up to you, the important thing is to
choose a logic and to keep it during all your project.
Using the approach b is more fine with me because in approach a you have written very few lines of code, but if there are many lines of code and many return statements, then are chances that i will somewhere use the wrong return type, where $return was assigned a some other place and i did not notice that.
I prever variant b. Not only is it more readable ( you know exactly that you do not need to consider any of the remaining code after a return statement), but it is also more failsafe.
If you either have a bug in the remaining code, or you encounter a set of conditions you did not take into account when designing the system, it would be possible that your result is changed. This cannot happen when you exit the function with return [$someVariable];
<?php
function theoreticalFunction( $var )
{
if( $something > $somethingelse ){
return true;
}
return false;
}
?>
This approach can also be used as on RETURN Statement, the program cursor is returned back and the next statement will not be executed.

Rationale behind elseif or elif statements in some languages

I'm not sure whether this is a good question, but this was just bothering me from a theoretical perspective. Can anyone explain why some languages like php have an explicit elseif/elif while others like c++ or java make do with just if and else. It would seem that less keywords to remember is preferable to more keywords. Is there any benefit to having an elseif statement available ?
P.S. I am writing a book on programming languages and I am collecting opinions on language design theory
EDIT: Thank you for pointing this out. I realize now that in Python specifically it is important due to the whitespace / indentation rule. I have changed my example from Python to PHP.
In my opinion, elseif avoids excessive indentations as #kalhartt commented, for python (mandatory) and for other languages like c++ (optional but customary).
But more importantly, I think elseif is a helpful feature that hints about the workflow in the sense that,
1) there is nothing else in the else branch, i.e. we don't have complicated structures like
if (A) {
}
else {
if (B) {...} else { ... }
i++;...
}
2) it helps to create a linear structure similar to the switch statement, where
switch (a) {
case 1:
...
case 2:
...
case 3
...
default:
}
maps to:
if (a == 1) {
}
elseif (a == 2) {
}
elseif (a == 3) {
}
else{
}
The if ... elseif ... form is a bit more verbose, but more powerful, i.e. with less stringent requirement on the conditional for each "case". For example, you can use
elseif (a > 3 && a < 7)
In my opinion, the benefit is to simplify code. Say there are a list of choices and you are using if statements to do an action per each different choice. It is easier to use elseif statements to narrow down the choices. Also, it has greater readability.

PHP Coding styles return; in switch/case

we're trying to implement new coding style guidelines for our team, the php codesniffer is printing an warning on switch case statements when no "break" is found like:
switch ($foo) {
case 1:
return 1;
case 2:
return 2;
default:
return 3;
}
is there any good reason to use :
switch ($foo) {
case 1:
return 1;
break;
}
?? the break is never reached ?
It's perfectly valid to leave out the break when you return from a switch.
But it's fairly common practise to add explicit breaks to every case as a defensive programming practise.
switch ($foo) {
case 1:
return 1;
break;
case 2:
return 2;
break;
}
The idea is that should you later change your code in case 1 and remove the return statement, you could forget to add a break.
That would accidentally cause program flow to fall through to case 2.
switch ($foo) {
case 1:
somethingDifferent();
case 2:
return 2;
break;
}
Falling through case statements is slightly unusual and you should add a comment to your code when you do it to show that it's intentional.
switch ($foo) {
case 1:
somethingDifferentAndWeWantToDoCase2AsWell();
// fallthrough
case 2:
return 2;
break;
}
As with many defensive programming practises you've got to balance whether the code bloat - which potentially clutters your code and make it less readable - is worth it or not.
If your "php codesniffer is printing a warning" try to get another better codesniffer and don't forget to try to use the last PHP stable version. You can, of course, write a breakafter one return, but it doesn't make sense, because it will never be read at all. Your code is OK.
Look at this:
$fun = function(int $argument): string {
switch ($argument) {
case 1:
return "one";
case 2:
return "two";
default:
return "more than two";
}
};
$str = $fun(4); // return "more than two"
In my opinion, this is simpler and better: fewer lines => less code to maintain :-)
To answer your question, no there's no good reason to have something that does nothing. Think about it this way, a comment after the return instead of a break saying "don't forget" will have the same affect - none. And put that way it sounds silly, right?
Unless you need to set a var to use later, I'd suggest the approach you have is perfectly fine. I knew the code's intent within 2 seconds from looking at it. Having a break just creates confusion.
There is no one size fits all really. The correct approach depends on whichever fits the scenario. Set a variable in each case and having a break may be the right way, or perhaps just return makes sense.
Some observations on other suggestions made in answers:
1) Not having a break after return means problems could arise if code is later changed
Whenever possible, code should be explicit, as well as readable and clear. We can also code in a way to make future changes easier. But in something as simple as a switch it should be no problem and need no safety net to refactor a case later to add or remove a return or break.
In fact, if you removed a return and "didn't notice there was no break" then that's a poor mistake and could be made in any part of coding. No gotcha checking will save you from that. And one should be very careful coding for future potentials, as that potential may never happen, or something else may happen, and you just end up maintaining obsolete code for years.
In the same vein this was argued to be a safety net for future changes - What if you remove the return and accidentally left in that safety net break when you should have removed it?
Even if this switch statement was a life or death scenario, really serious code, I would be against adding the "pointless" break after the return. Just make sure whoever was working on the code knew what they were doing, and it was code reviewed by enough eyes and tested fully.
If it was that serious, then you'd have additional checks in place better than a proposed safety net to catch sloppy devs.
To argue that break after return adds a safety net, means you're not coding or testing properly. If this is a safety net deemed useful then it's likely there are tons of bugs in the code in potentially more serious places.
The wiki article of "Defensive Programming" was linked to, but it's not relevant here:
Defensive programming is a form of defensive design intended to ensure
the continuing function of a piece of software under unforeseen
circumstances.
Leaving a safety net break in is not a scenario of unforeseen circumstances, nor defensive programming. It's just bad coding, and you can't litter your code with back up code just in case you don't code correctly when you change something. That's such a bad approach to coding. The argument that "if someone removed return it won't work", well you could also have a typo in the case var, or forget to write the case, or...
The return returns, and you don't code "defensively" to avoid a return failing. That would mean PHP is broken, and you aint gonna fill your code with safety nets to cater for that. That's something you have on a much higher level up.
2) break after return keeps it explicit
But it's explicitly wrong. The return returns, so the break won't happen. To me that is scratch head time wondering if I've missed the intent - not for long as it's clear what will happen, but there will be a moment where I ponder it to make sure I've not missed something.
While it's not invalid or error to have a return and then break in the same case, it's just entirely pointless as the break does nothing. It's pointless code that needs to be seen, maintained, and figured out as it's not logical.
If explicit is the core goal and having a break after a return urks you because it's pointless, then I'd say it'd be better to set a variable and break, then return the variable after breaking from the switch.
Like #RageZ answer https://stackoverflow.com/a/1437476/2632129
3) Set a variable and return after the switch statement is completed
There's nothing wrong with this approach at all, but if there's no reason to store the value in a variable (later use etc) then it's good to return immediately when there's no need to hang around to do anything else.
That shows clear intent - return a value as soon as the case is matched.
I have much better solution.Please follow below code for above switch statment:
$result = 3; // for default case
switch ($foo) {
case 1:
$result = 1;
break;
case 2:
$result = 2;
break;
default:
// do nothing
}
return $result;
It will not result in any error and code is also fine with concepts.
I am not an expert in perfect coding but I think the validator would prefer something like that
switch ($foo) {
case 1:
$ret = 1;
break;
case 2:
$ret = 2;
break;
default:
$ret = 3
}
return $ret
I think using return in case statement to break the flow of the code is not really a best practice. So that's why the validator say there is no break ...
For your question about at category, I don't know ... sorry
From the PHP manual (http://us3.php.net/manual/en/control-structures.switch.php) :
PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:
<?php
switch ($i) {
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
case 2:
echo "i equals 2";
}
?>
Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).

Are singleline if statements or if statements without braces bad practice?

if (condition) { /* do something */ }
else { /* do something */ }
if (condition)
/* do something */
else
/* do something */
I was told that the first instance wasn't a good idea. I have no idea whether this is really this case (or for the second one either); does it not shorten the amount to type? Or is it because it just makes a mess?
The best practice is to write code that others can read and update easily.
Your first form is questionable because it doesn't follow the forms that most PHP developers are used to:
if (condition) {
// code
} else {
// code
}
// ... or ...
if (condition)
{
// code
}
else
{
// code
}
// ... or ...
if (condition) { /* short code */ } else { /* short code */ }
// ... or ...
condition ? /* short code */ : /* short code */;
Note that this is entirely about standard practice, and doesn't necessarily make senseā€”it's only about what other developers are used to seeing.
Your second form, more importantly, isn't so good because it makes it easy for another programmer to make this mistake:
if (condition)
// code A
else
// code B
// code C (added by another programmer)
In this example, the other programmer added code C, but forgot to wrap the whole else block in braces. This will cause problems. You can defend against this by simply wrapping your if and else blocks in braces.
My preference if for consistency... so:
if(...)
{
statement 1;
statement 2;
}
else
{
statement 1;
statement 2;
}
is no different than:
if(...)
{
statement 1;
}
else
{
statement 1;
}
So I always use them because it is consistent and it avoids problems forgetting to add them in later.
However other people will look at my code and think that it is stupid to put in the { and }. They have their reasons, I have mine... I happen to like my reasons more than I like theirs :-)
Generally non-readable code is a bad practice. The single line is more efficient in your typing and saves line numbers but come back to it a year from now or while you're scanning for bugs and it'll make it more difficult.
In my opinion, yes it's bad practice to have single line if statements.
The computer doesn't really care (as far as I can tell) but you should always write your code like it's going to be maintained by a serial killer that knows where you live.
Readable! Easily self-discernable.
The problem I've seen is developers not recognizing the {}-less-if when they add code to one of the conditions. Example:
//before
if(something)
statement;
//after
if(something)
statement;
addedstatement;
Obviously, this won't do what they expect.
Have you ever seen code like this in C or C++?
/* Warning: bogus C code! */
if (some condition)
if (another condition)
do_something(fancy);
else
this_sucks(badluck);
Either the indentation is wrong, or the program is buggy, because an "else" always applies to the nearest "if", unless you use braces.
(Let's just use python. No brackets, just pure clean whitespaces. :P)
For all but the shortest statements, use the braces and space them accordingly. You want to do this for a few reasons:
It's harder to make a mistake about where something goes.
It's easier to read.
In languages with macro-expansion facilities (e.g. C, C++), failure to include braces will cause confusing logic errors when a macro containing multiple statements is expanded inside of an unbraced if-else.
One major benefit of using multiple lines is ease of debugging. If you have an if else statement all on one line and the debugger tells you that line x blew up, it's more difficult to determine which part of the statement failed. Multiple lines also makes it easier to step through your code using a debugger.
Those are two lines long, so not really a single line.
There's nothing wrong with single line ifs when it makes the code easier to read.
For example, something like this:
if (last_item) print ", and " else print ", "
is much better than
if (last_iem)
{
print ", and "
}
else
{
print ", "
}
This is more coding style than anything else. That said, my personal opinion is that your second example is potentially quite harmful. It's easy enough to accidentally "add a second line to the block" in languages where braces are the only way to create blocks. But in PHP, where an alternate syntax exists, this is even less likely to set off the necessary warning bells:
if ($_GET["asdf"]==1):
/* do something */
else:
/* do something */
endif;
Rule of thumb: if you're going to put your "do something" on a separate line, use braces; if you're not going to use braces, put it on the same line!
I have seen so many third party code with silly issues, that I prefer to use braces all the time. That said I have never felt good on
if(){}
else (){}
I use if(){} on the same line when it is a short instruction and it is alone. If there is an else use the long:
if(checkSomething)
{
//dosomething
}
else
{
//doanotherthing
}
This is something that I actually remember from an employment exam a while back. The code was similar to the following:
if (x == 0)
x = 2;
else
print("x is: %d", x); // debugging!
x = 4;
Most people here can spot the error, but you can really substitute in anything you want as the "bad code" that was inserted. The more subtle error comes when you have an "old version" of something commented out, and somebody un-comments it, and suddenly the second statement is outside the block.
Basically, unless it's a small test application to learn a concept fast, I always bracket (and even in the test apps I usually bracket). It just isn't worth the headache later if I don't, even in 5-line-methods.
You should put the "if" and the "do something" on separate lines to make your code friendlier to interactive debuggers.
If you put both the "if" and "do something" on the same line, then you can't set a breakpoint just on the "do something" line.

Categories