Jump to content
Larry Ullman's Book Forums

Your Thoughts On Using One Line If Statements


Recommended Posts

Guest Deleted

Hey guys, I have a PHP question based on something I just read in the Modern Javascript book. Here's what I read: ""With if-else and if-else if conditionals, you can omit the curly braces if only a single line of code is to be executed, but I highly recommend that you never do this." (Emphasis added.)

 

This sounds like something I do sometimes in PHP and I wondered what the rationale is for not doing it.

 

Okay, 99% of the time when I use if/if else if/if else statements in PHP, I use curly braces but sometimes I have something so simple that I just do this:

 

if (condition is true) do something simple;

 

Do you guys recommend against this? If so, why?

 

Thanks in advance.

Link to comment
Share on other sites

There's no right answer, but always using curly braces is (I think) clearer, more consistent and makes your code easier to read.

Furthermore, I think Larry recommends that in the JS book in particular because the most popular JS code checking tool, JSLint, will throw an error if you don't use curly braces every time.

Link to comment
Share on other sites

Every coder should be striving to write the most legible code they can, for both themselves and others. Ask yourself how easily and quickly could you read and understand what the code does if you came back to it in 6 months. My view is, always use curly braces.

 

Also, understand that projects often have their own code style rules. I have my own preferences but I’ve found myself having to write code differently because I wanted to contribute to certain open-source projects.

 

I’d recommend having a look at PSR http://www.php-fig.org/psr/psr-1/

 

 

“Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live.”

— Martin Golding

Link to comment
Share on other sites

I agree on the notion of following standards. With that said, there are no rules without exceptions. I think one-liner if statements are far more readable when you need to assert on state.

public function someMethod( SomeClass $something )
{
    if ( ! $this->assertSpecificState($something) ) return;

    // No need to worry about the unwanted state. 
}

While the above could be written on several lines, it's very expressive yet keeps the noise ratio down.

Link to comment
Share on other sites

 Share

×
×
  • Create New...