Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

How should indentions of if-statements be handled? #52

Closed
sattes-faction opened this Issue · 9 comments

7 participants

@sattes-faction

Say I'm having an if-statement with many arguments like this:

<?php
if ($longExpression && ($anotherCondition || $yeAnotherCondition)) {
    // if body
} else {
    // else body;
}

How should/could this be indented?

<?php
if ($longExpression &&
    ($anotherCondition
    || $yeAnotherCondition)
) {
    // if body
} else {
    // else body;
}

Maybe you could add a hint on how this should be done. Me and my colleagues are always discussing about this one.

@sergeylukin

I'm also interested to know FIG's opinion regarding this.

sattes-faction, you're missing one curly brace in every example.

@sergeylukin

Update: sorry,only in one example

@sattes-faction

Oh, you're right -thanks for the hint! I edited the post.

@GodsBoss

I think they shouldn't. If an if statement is so long it needs a linebreak, a function or preferably method should be created and the if statement should be rewritten:

if ($this->isThisRight()){
    // ...
@pmjones
Owner

If you find that a condition runs longer than the allowed line length, or if the condition is easier to read when indented, you probably want to use an "explaining variable" in the condition. Extract the condition to a variable, then test the variable.

For example:

$ok = $longExpression
   && ($anotherCondition || $yetAnotherCondition);

if ($ok) {
    // ...
}

This is neither approved nor prohibited by PSR/FIG.

@sebinsua

^ I like the above but I think it's preferable to use a variable name which is more descriptive. $ok is sloppy.

@pmjones
Owner

Agreed. Note that it was slapped together as a basic response to illustrate a concept, not as a paradigm of virtue. ;-)

@Incognito

My instincts say this should be left free-form, where typically quality code will be broken into logical units by vars and methods/funcs, and the more free-form everything-at-once code will be slammed into a huge IF.

My motivation is that really breaking a huge chain of bitwise and binary ops into multiple lines isn't a gain for clarity by any order of magnitude... ie, if you have this problem, whitespace isn't going to help you.

Also, for the ultra-rare case where it makes sense to do this, the whitespace may actually hinder readability.

If anything, braces '(' and ')' should match with indentation some how... yet even that leaves me doubtful of improving readability.

@dragoonis
Owner

The original question has been answered. With 6 months inactivity, I'm closing this.

@dragoonis dragoonis closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.