[moved from
https://groups.google.com/d/topic/php-fig/URel8dbxsTE/discussion]
Hello PHP enthusiasts,
I recently was in a situation where I had to tell a novice how to write code that would not look too messy.
I came across an if statement with some complex checking - quite long too - and the
Control Structure section of PSR-2 doesn't give specific information on this case.
My
question would be, where does the PHP-FIG stand on this matter ? Or on
what do they disagree ? I can think of several alternatives :
if ($var1 && $var2 || ($varX % $varY == 1)) {
// ...
if ($var1 &&
$var2 || ($varX % $varY == 1)) {
// ...
if (
$var1
&& $var2
|| ($varX % $varY == 1)
) {
// ...
These
are the combinations of the nicest and ugliest things I could think of
right now. The last one seems the nicest to me, if the first one isn't
possible.
Thank you for your involvement.
And the "relevant" answers from there :
On Monday, January 28, 2013 1:06:12 AM UTC+1, Sebastian Krebs wrote:
Hi,
Just
want to point out, that you consider refactoring, when you face too
complex conditions. That something looks messy is not always a question
_how_ it is written, but _what_ is written.
My opinion: When it is not too long (let say 120, or
sometimes 150 characters), than everything should on one line, else I
use the last one. It's easier to overview, when the operator, that
connects the single conditions together, is not hidden at different
positions at the end of every line.
Regards,
Sebastian
On Monday, January 28, 2013 3:08:35 AM UTC+1, pmjones wrote:
There is no existing PSR that expresses a recommendation on this matter.
It my personal opinion, as I have stated earlier elsewhere, that
this is a classic candidate for "extract to explaining variable."
Instead of leaving the entire condition set inside the parenthesis,
extract it to a variable and then use the variable as the condition.
For example:
$cond = $var1
&& $var2 || ($varX % $varY == 1);
if ($cond) {
// ...
}
Hope that helps.
-- pmj
On Monday, January 28, 2013 7:47:59 AM UTC+1, Andreas Möller wrote:
Further to what Paul suggested, have a look at Martin Fowler's catalog of refactorings:
Nonetheless,
when it comes to statements like that, I introduce a new line and
indent before the operator (similar to string concatenation and usage of
the ternary statement).
Best regards,
Andreas
On Monday, January 28, 2013 8:02:03 PM UTC+1, Sherbrow wrote:
Finally, it seems that I should use one single line if it "fits" and
still easy to understand (quite obvious) or introduce variables. The
question of line breaks and indentation is still the same with variables.