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;.
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.
In PHP, I do know curly brackets are not required for one-statement conditionals. But this question is about good coding style. (Of course when talking about style, it's usually better to just use whichever style is consistent within the project, but let's ignore that for this question.)
So: Is it better form to enclose any conditional statements in curly brackets, or is it better (e.g. more clean) to not use brackets in simple conditions:
E.g. this:
if (!file_exists($templatefile)) {
throw new Exception('Template file does not exist');
}
or this:
if (!file_exists($templatefile))
throw new Exception('Template file does not exist');
Are there any common consistent good practices for this, or is it just up to personal preferences?
I have seen way too many mistakes by people who do not use the curly brackets and then, later on, add an additional command and forget to wrap it.
My attitude is to wrap it for readability and future extensibility.
One rule in good coding style is: Avoid distraction. So having a common way to do this - regarless of single- or mutliple-lines is the way to go:
if (!file_exists($templatefile)) {
throw new Exception('Template file does not exist');
}
Sure, this is subjective (but that's a problem with your question), not all programmers are distracted by that. But by fact, your version control system will be. If you need to change a single-line if-block into a multiline one, do you need to touch the if condition? Hell no, because it did not change, right? But if you don't use the brackets, you still need to touch that line. That's what I would call distraction as well. So this is the less subjective argument to give.
As you can imagine, there are other arguments you can foster this approach with, like when you need to debug code and you need to switch from one to mutli-line for various changes etc. pp. So keep it aligned in your whole codebase, if it is the if block, it is the if block.
For the fun, the always throw "if" block:
if (!file_exists($templatefile)); {
throw new Exception('Template file does not exist');
}
It depend from developer to developer, it all up to you.
Just follow any one approch in your code, do not mix it up which would create problems in future
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.
I was looking through many snippets of code, and I have found that people can use the following two methods in an if statement:
Method 1:
<?php
if ($condition) {
// Do this
}
?>
Method 2:
<?php
if ($condition):
// Do this
endif;
?>
So which method is more compatible with PHP compilers and versions with PHP, or is there no discernible difference between the two?
Most of the time the alternative (endif) syntax is used in view scripts. It's often hard to see/notice the end of an if statement since a curly brace only takes up one character, when you're at the bottom of a file, it's hard to tell if it's the end of an if or a foreach. For example:
<?php if ($condition): ?>
<div>a huge block of html</div>
<?php endif; ?>
They are both exactly equivalent. Consult your organization's style guide to determine which you should use.
This alternative syntax is in no way different than the, perhaps, more familiar syntax. Just don't mix the two. Similar syntax exists for while, for, foreach, and switch.
Typically you should choose your preferred syntax based upon readability, and your teams preference.
What really might throw you is when you begin to see "if statements" which misuse logical conjunction operators like the following:
isset( $value ) AND print( $value );
As I've seen until now, in my app, there is no difference between them, but you can have a lot of problem if you'll mixt them without a rule because it's possible to get some errors and you will search a curly but you have not used curly.
Choose one syntax an use exclusive.
The only difference is seen in very large documents and projects. My company uses braces rather then endif, endelse... as we work on very large projects. When you compare file sizes there is a benefit to using braces. Smaller files load faster so we work to reduce every byte we can. We comment out the end brace to make it easier to identify on testing and then delete all comments for production.