As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
When I started developing, I followed tutorials that always used {} (curly braces) to enclose blocks. However, when I began looking at other peoples code (classes on GitHub for example, or just more code in general than what a basic tutorial would show), however I've also seen block statements without being enclosed in {}, for example;
if($var < 15)
$string = 'Hello, Jimmy!';
elseif($var >= 15)
$string = 'Hello, Anne!';
Is the same as
if($var < 15) {
$string = 'Hello, Jimmy!';
} elseif($var >= 15) {
$string = 'Hello, Anne!';
}
I've never used blocks not enclosed in {}, however I used them today and I'm starting to see the efficiency of doing so (it looks a lot cleaner too, as I'll often find my functions riddled with {} from loops, conditionals etc.
What I'm asking is;
a) are there any limitations on blocks without curly braces (; I noticed my IDE dropped back from an indent after I enter a single line and returned after an if() conditional?
b) are there any best practices to be had, when not using {}?
Any answers, specifically those inc. background/docs on the convention of curly brace usage for blocks vs. not using them would be greatly appreciated, as I'd really like to understand the usage of curly braces :)!
Best practice is to always use them. It's far too easy for another developer to come along and add a line of code or delete a line of code and completely break the conditional unintentionally.
You can omit the {} for one single line:
if(something)
do something else
however you cannot omit it and have it keep going like so:
if(something)
do one thing
do another
do some more
The example above would only have 1 conditional element (the 'do one thing'). The rest would just run unconditionally.
And yes I've seen the sloppy method before without the {}, I myself prefer using {} to separate the logic, and its easier to read.
So stick to using {} in your code.
It mostly depends on the style you are used to. http://en.wikipedia.org/wiki/Indent_style
if (some_error)
something(); //Will be executed only when some_error==true
somethingelse(); //Will always be executed.
If you don't use braces only the next line is part of the if statement.
if (some_error) err1 = "bad1"; errorno=3;
Of course, in the above example, errno will always be 3 whether or not some_error is true or not.
It is the same with for loops
for (i = 0; i < 10; i++)
doSomething (i);
So the braces marks where it starts and where it ends. Not using them means that only the next line will be affected by the if, for, while, ... statement.
Also, braces can be used to mark block of code. When i code in C++ i always mark the start and end of a GL call with braces.
glBegin(GL_TRIANGLES); // Drawing Using Triangles
{
glVertex3f( 0.0f, 1.0f, 0.0f); // Top
glVertex3f(-1.0f,-1.0f, 0.0f); // Bottom Left
glVertex3f( 1.0f,-1.0f, 0.0f); // Bottom Right
}
glEnd();
This way it is easier to read and to spot missing glEnd calls.
Curly braces are optional if the statement to be executed after the conditional or loop is only a single line:
//This outputs "hello"
$test = 1;
if($test == 1)
echo "hello";
//This outputs "howdy"
$test = 1;
if($test == 2)
echo "hello";
echo "howdy";
Whether or not you surround single-line statements with braces is a matter of personal preference and also may be dictated by a coding style document if you're working on a collaborative project. Personally I never use them for single statements and allow indentation of my code to show how the code is organized but if you see my second example above this is a case I've seen before where bugs creep in. The coder creates a conditional with a single line to be executed based on that condition. Then another coder goes in and adds a second line but forgets to add the braces. So from that perspective you could say to always use them. It depends much on your individual circumstances.
You only have to use them if there is more than one line of code following a curly brace.
if($var) return true;
same as
if($var) {
return true;
}
However, if you have more than one line you must enclose them in curly braces.
if($var) {
$var += 1;
$var2 = $var;
return $var2
}
Personally I stopped using them when one line of code followed because you are right, it looks cleaner especially if its all on one line like the top statement. Also too, your code will be more manageable if you cut down on the else if statements and just use return to stop the function if the if fails and just keep going to the next if on true. It can get really messy real quick with a lot of else if statements` and your not using a switch. Other than personal preference, if it's just one line of code following, lose the braces.
AlienWebguy is right when it comes to professional development, use them in that case.
Related
I've never been a fan of brackets in control structures and only today I realised how it only accepts one statement within a bracket less if condition, if I have more than one statement it will throw a syntax error. Is this how PHP works or can it be something wrong with my IDE?
Obviously the error is clear but I just want to make sure this is normal.
If you have any other any links to other alternate syntax let me know please.
Bellow is just something I pasted from a project am doing and example of the syntax error.
if($this->reel3 = 1)
parent::addCash($this->$bet*2);
print(parent::getCash()); // < Line throwing the syntax error
else
// TODO
EDIT (FURTHERMORE)
After looking at some of the answer and comments I was wondering how its done in a professional environment, I know this is more about taste but I want to know from the professional out there if the style of the syntax matters?
Would
if(condition)
{
//something
} else {
//something
}
be better than
if(condition):
//something
else:
//something
endif;
or any other way of writing the same piece of code?
This is how php works. If you don't put brackets around your if statement only the next statement is in the if block all other follow up statements are outside of it. But since you have a else block after it you will get a error.
(BTW: You make an assignment in the if block, so this will be always true)
Look at these 2 examples:
if($this->reel3 = 1)
parent::addCash($this->$bet*2); //In the if statement
print(parent::getCash()); //Outside the if statement
else
Same as:
if($this->reel3 = 1) {
parent::addCash($this->$bet*2);
}
print(parent::getCash());
//^^^^^ I think here it's more clear to see that this will give you a error, since it's between the if and else block which is not allowed
else { }
For more information about the control structure if see the manual: http://php.net/manual/en/control-structures.if.php
Take a look at the answer of this question:
PHP conditionals, brackets needed?
And yes, it is PHP, not your IDE!
This is perfectly normal of all programming languages that use brackets rather than indentation to designate blocks of code. Without the brackets, there is no way for the interpreter to know which lines are part of the if block and which aren't. The one-line if-block is a convenient shortcut: if you don't include any brackets, PHP like many other languages will treat the single line directly following the if statement as the body of the if block.
Note PHP does have an alternative syntax for if statements as well, using colons instead of brackets, but that's a story for another day.
Is it possible to enclose code fragments in PHP within brackets (without using the fragment as a function)?
Would the following code behave the same way as it would without the curly brackets? Or might there be any problems depending on what kind of code used inside or outside the brackets?
For example, will this:
<?php
// First Code-Block
{# several lines of code
}
// Second Code-Block
{# another several lines of code
}
?>
Always behave the same way as this:
<?php
// First Code-Block
# several lines of code
// Second Code-Block
# another several lines of code
?>
Update:
One of the goals, as stated in "My1"'s comment as well, is to structure large code sections. Especially since most IDEs give you the option to collapse the lines between the brackets.
Especially in consideration of "dragondreamer"'s "Luke Mills"'s answers I played around with it a bit, and so far I didn't encounter any side effects. Of course, this might change with new PHP Versions in the future but "Luke Mills"'s answer gives good pointers on what to keep an eye on.
Yes, but it won't create a new local scope. It's not something that would normally be done. Usually people mark blocks like this with comments.
Update:
It took a bit of digging to find a reference to it in the manual, but here it is:
http://www.php.net/manual/en/control-structures.intro.php
Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. The various statement types are described in this chapter.
The key here is statements can be grouped into a statement-group by encapsulating a group of statements with curly braces.
I also had a look for a reference to variable scope as it relates to this situation, but the manual doesn't specifically mention it, however you can think of it like this:
In PHP, functions and classes create a variable scope. You can read about that here. But a statement-group (as described above) does not. Don't think of the curly braces of a statement-group like the function (or class) wrapping brackets, but think of them like the curly braces that wrap the statement-group of control structures (if, for, while, switch, etc.) - because that's exactly what they are. It's clear that if you're using an if statement (or any other control structure) that the braces don't introduce a new scope, they are simply wrappers for a block of statements.
PHP code behavior does not change if you enclose it within curly brackets. However, you can't use some PHP statements inside curly brackets:
namespace declarations;
namespace use declarations to alias or import any names;
global const declarations;
__halt_compiler().
This means, the following script will work:
<?php
const x = 5;
echo x;
but the following will not compile:
<?php
{
const x = 5;
echo x;
}
In one project I'm working on, I use statement-groups to indicate structure - in my case, parent/child relationships between nodes creates in a router:
$router = new Router();
$admin = $router->route('admin');
{
$upload = $admin->route('upload')->post('upload');
$menu = $admin->route('menu');
{
$menu->route('load')->get('load');
$menu->route('save')->get('save');
}
}
```
Internally, this builds a hierarchical structure like:
/admin
/upload
/menu
/load
/save
Calling route() in this example creates a child - so the code creates a model (inside the router) which has a tree structure, but the structure of the code does not reflect that.
I'm using curly braces here to make the code more legible, since reading the code without curly braces and indentation would be quite difficult:
$router = new Router();
$admin = $router->route('admin');
$upload = $admin->route('upload')->post('upload');
$menu = $admin->route('menu');
$menu->route('load')->get('load');
$menu->route('save')->get('save');
Indentation in this case really clarifies what's happening, I think.
I also do this, solely because of my text editor (Komodo Edit 8.5). It's not a "bad reason" or "bad coding", if it helps you and doesn't cause any problems and if there's no other easy way to do it.
I solve the problem with a work-around:
if(1 == 1){ //always executing if function
//whatever you want to add
}
#
adding a # at the end prevents my editor from collapsing all empty lines below the curly brackets. This helps to further structure the code.
Is it possible to enclose code fragments in PHP within brackets (without using the fragment as a function)?
Would the following code behave the same way as it would without the curly brackets? Or might there be any problems depending on what kind of code used inside or outside the brackets?
For example, will this:
<?php
// First Code-Block
{# several lines of code
}
// Second Code-Block
{# another several lines of code
}
?>
Always behave the same way as this:
<?php
// First Code-Block
# several lines of code
// Second Code-Block
# another several lines of code
?>
Update:
One of the goals, as stated in "My1"'s comment as well, is to structure large code sections. Especially since most IDEs give you the option to collapse the lines between the brackets.
Especially in consideration of "dragondreamer"'s "Luke Mills"'s answers I played around with it a bit, and so far I didn't encounter any side effects. Of course, this might change with new PHP Versions in the future but "Luke Mills"'s answer gives good pointers on what to keep an eye on.
Yes, but it won't create a new local scope. It's not something that would normally be done. Usually people mark blocks like this with comments.
Update:
It took a bit of digging to find a reference to it in the manual, but here it is:
http://www.php.net/manual/en/control-structures.intro.php
Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well. The various statement types are described in this chapter.
The key here is statements can be grouped into a statement-group by encapsulating a group of statements with curly braces.
I also had a look for a reference to variable scope as it relates to this situation, but the manual doesn't specifically mention it, however you can think of it like this:
In PHP, functions and classes create a variable scope. You can read about that here. But a statement-group (as described above) does not. Don't think of the curly braces of a statement-group like the function (or class) wrapping brackets, but think of them like the curly braces that wrap the statement-group of control structures (if, for, while, switch, etc.) - because that's exactly what they are. It's clear that if you're using an if statement (or any other control structure) that the braces don't introduce a new scope, they are simply wrappers for a block of statements.
PHP code behavior does not change if you enclose it within curly brackets. However, you can't use some PHP statements inside curly brackets:
namespace declarations;
namespace use declarations to alias or import any names;
global const declarations;
__halt_compiler().
This means, the following script will work:
<?php
const x = 5;
echo x;
but the following will not compile:
<?php
{
const x = 5;
echo x;
}
In one project I'm working on, I use statement-groups to indicate structure - in my case, parent/child relationships between nodes creates in a router:
$router = new Router();
$admin = $router->route('admin');
{
$upload = $admin->route('upload')->post('upload');
$menu = $admin->route('menu');
{
$menu->route('load')->get('load');
$menu->route('save')->get('save');
}
}
```
Internally, this builds a hierarchical structure like:
/admin
/upload
/menu
/load
/save
Calling route() in this example creates a child - so the code creates a model (inside the router) which has a tree structure, but the structure of the code does not reflect that.
I'm using curly braces here to make the code more legible, since reading the code without curly braces and indentation would be quite difficult:
$router = new Router();
$admin = $router->route('admin');
$upload = $admin->route('upload')->post('upload');
$menu = $admin->route('menu');
$menu->route('load')->get('load');
$menu->route('save')->get('save');
Indentation in this case really clarifies what's happening, I think.
I also do this, solely because of my text editor (Komodo Edit 8.5). It's not a "bad reason" or "bad coding", if it helps you and doesn't cause any problems and if there's no other easy way to do it.
I solve the problem with a work-around:
if(1 == 1){ //always executing if function
//whatever you want to add
}
#
adding a # at the end prevents my editor from collapsing all empty lines below the curly brackets. This helps to further structure the code.
So pragmatically, I've got a quick and dirty answer to what I'm looking for here. But why isn't using that a good idea? Why can't I find any formal documentation of it? Is it not part of the spec and standard? Is it not widely supported? Is it just because minification could break code using that syntax?
If you could point me to more comprehensive docs of the feature, I'd appreciate that. What defines the contents of the if block? Is it indentation based? If it was, that'd be interesting.
On another note, is there something similar to this syntax for if statements in PHP? I can swear that I've seen them being used here and there, but I can't find any examples off hand. Am I just crazy and it actually doesn't exist in PHP, or can those types of if blocks be used in PHP? Does such an if block support having an else as well, both in JS and PHP?
It seems that there's an indentation based one as well as a single-line based syntax as well. What can you tell me about the following?
if(condition) do_some_statement();
Thanks
But why isn't using that a good idea?
Because it's hard to maintain.
Why can't I find any formal documentation of it? Is it not part of the spec and standard?
Of course it is, see §12.5 - The if Statement and §12 - Statements in the spec. The body of an if is a Statement. One kind of Statement is Block (§12.1), which allows a list of statements to be treated as one statement, but there are many other kinds of statements.
Is it not widely supported?
Universally.
Is it just because minification could break code using that syntax?
A good minifier won't break that syntax. (A good minifier will make use of it, in fact.)
What defines the contents of the if block? Is it indentation based?
The body of an if statement consists only of the statement following it, indentation has no significance in JavaScript. So all of these are equivalent:
if (foo)
bar();
charlie();
if (foo) bar();
charlie();
if (foo)
bar(); charlie();
if (foo)
bar();
charlie();
In the above, only the call to bar is conditional on foo; charlie is called regardless.
That's why we have Block, the Statement that introduces a list of statements to be treated as a unit (a block, you might say :-) ):
if (foo) {
bar();
}
charlie();
if (foo) { bar(); }
charlie();
if (foo) {
bar(); } charlie();
if (foo)
{ bar(); }
charlie();
Indentation is important for humans, though, so keeping consistent indentation is a good idea. The first example in each of the above is probably clearest (of the ones listed) for us mere mortals. :-)
On another note, is there something similar to this syntax for if statements in PHP?
I'm not a big PHP-head, but it looks identical, defined in Control Structures - if. There are examples with and without {}. (There's also a different, alternative syntax I won't go into here.)
Does such an if block support having an else as well, both in JS and PHP?
Yes, if supports else both with and without blocks.
javascript is not white space sensitive, meaning
if(condition) do_some_statement();
is the same as
if(condition)
do_some_statement();
that being said, omitting braces in a single line if statement is always frowned upon because it can lead to bugs if the if statement ever needs to be modified:
if(condition)
do_some_statement();
// someone adds another line here, without adding the braces
// now you've introduced a bug
also, is it really that hard to write { }? :P
The statement following an if is just that: a statement.
One of the possible forms a statement can take is that of a brace-enclosed group of statements.
Thus, the syntax of an if statement is
if ( expression ) statement
Thus the reason that braces improve maintainability is that they provide an explicit boundary to the scope of influence of the if control flow effect.
why isn't using that a good idea?
It is far to easy to add another statement and expect it to only fire if the if passes
Why can't I find any formal documentation of it?
The MDN documentation:
Statement that is executed if condition evaluates to true. Can be any statement, including further nested if statements. To execute multiple statements, use a block statement ({ ... }) to group those statements.
ECMA-262 (page 89):
if ( Expression ) Statement
It seems that there's an indentation based one
No. Just an if, then a condition, then a statement. The statement can be formatted on the same line or the next line.
White space is not significant in JS.
It is standard, part of the spec (if-statement, other statements) and supported everywhere. Minification does not break it, because whitespaces have no semantics in JS - it even will enforce it for one-line-statements to save the two braces.
So, it is widely used (without problems!) as well. Sometimes it is considered bad because appending statements to the indented body without adding the braces can lead to problems. Also, it can lead to erratic behaviour when used in nested ifs:
if (false)
if (whatever)
;
else
alert("");
Would you have expected an alert? No, the else belongs to the last if.
Yet, you can use it unconcerned for one-line-statements that are sure not to get extended, like return;.
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.