Reputation: 3291
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?
Upvotes: 4
Views: 716
Reputation: 197832
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');
}
Upvotes: 2
Reputation: 9
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
Upvotes: 0
Reputation:
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.
Upvotes: 10