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 post
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 post
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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...