Добро пожаловать на форум PHP программистов!
За последние 24 часа нас посетили 17199 программистов и 1838 роботов. Сейчас ищут 1539 программистов ...

Split long if statements onto several lines

Вернуться к: Coding standard enhancements

Split long if statements onto several lines

Long if statements may be split onto several lines when the character/line limit would be exceeded. The conditions have to be positioned onto the following line, and indented 4 characters. The logical operators (&&, ||, etc.) should be at the beginning of the line to make it easier to comment (and exclude) the condition. The closing parenthesis and opening brace get their own line at the end of the conditions.

Keeping the operators at the beginning of the line has two advantages: It is trivial to comment out a particular line during development while keeping syntactically correct code (except of course the first line). Further is the logic kept at the front where it's not forgotten. Scanning such conditions is very easy since they are aligned below each other.

<?php

if (($condition1
    
|| $condition2)
    && 
$condition3
    
&& $condition4
) {
    
//code here

?>

The first condition may be aligned to the others.

<?php

if (   $condition1
    
|| $condition2
    
|| $condition3
) {
    
//code here
}
?>

The best case is of course when the line does not need to be split. When the if clause is really long enough to be split, it might be better to simplify it. In such cases, you could express conditions as variables an compare them in the if() condition. This has the benefit of "naming" and splitting the condition sets into smaller, better understandable chunks:

<?php

$is_foo 
= ($condition1 || $condition2);
$is_bar = ($condition3 && $condtion4);
if (
$is_foo && $is_bar) {
    
// ....
}
?>

There were suggestions to indent the parantheses "groups" by 1 space for each grouping. This is too hard to achieve in your coding flow, since your tab key always produces 4 spaces. Indenting the if clauses would take too much finetuning.



Вернуться к: Coding standard enhancements

© 2024 «PHP.RU — Сообщество PHP-Программистов»
Главная | Форум | Реклама на сайте | Контакты VIP Сувениры
Разработка компании ODware