In php, should curly braces be used even in short conditional statements?

In PHP, I know that curly braces are not required for conditional statements. But this question is about a good coding style . (Of course, when it comes to style, it is usually best to use any style agreed upon within the project, but ignore this for this question.)

So: is it better to enclose any conditional operators in curly braces or is it better (for example, cleaner) not to use brackets in simple conditions:

eg. this is:

if (!file_exists($templatefile)) { throw new Exception('Template file does not exist'); } 

or that:

 if (!file_exists($templatefile)) throw new Exception('Template file does not exist'); 

Are there any general agreed recommendations for this, or does it depend only on personal preferences?

+4
source share
3 answers

I saw too many errors on the part of people who do not use curly braces, and then adding an extra command and forgetting to wrap it.

My attitude is to wrap it for readability and future extensibility.

+10
source

One rule in good coding style: Avoid distraction. Thus, to have a common way to do this - without a single or multi-line line - is the way to go:

 if (!file_exists($templatefile)) { throw new Exception('Template file does not exist'); } 

Of course, this is subjective (but this is a problem with your question), not all programmers are distracted by this. But actually your version control system will be. If you need to change a single-line if-block to a multi-line one, do you need to touch the if condition? Damn, no, because that hasn't changed, has it? But if you do not use parentheses, you still need to touch this line. This is what I would call a distraction. So this is a less subjective argument.

As you can imagine, there are other arguments with which you can reinforce this approach, for example, when you need to debug code, and you need to switch from one to mutli-line for various changes, etc. So, keep it in line with your whole code base, if it's an if block, it's an if block.

For fun, always drop the "if" block:

 if (!file_exists($templatefile)); { throw new Exception('Template file does not exist'); } 
+2
source

It depends on the developer to the developer, it all depends on you. Just follow any convention in your code, don't mix it up, which will create problems in the future.

0
source

Source: https://habr.com/ru/post/1479494/


All Articles