How to write long IF more prettier?
I have long IF:
if(rand(1, 开发者_如何转开发100) == 22 && $smth < time() &&
$smths > 5 && $sxsxsx > 250 &&
!$_SESSION['false'])
{
echo "wow, big if just happened!";
}
How to write it more "prettier"?
I prefer breaking before the boolean operators.
if(rand(1, 100) == 22
&& $smth < time()
&& $smths > 5
&& $sxsxsx > 250
&& !$_SESSION['false']
)
I like to name my conditions and group them so its clear what their purpose is.
$is22 = rand(1, 100) == 22;
$someTime = $smth < time() && $smths > 5;
$meetsSx = $sxsxsx > 250;
$inSession = !$_SESSION['false'];
if ($is22 && $someTime && $meetsSx && $inSession) {
// do something
}
$isSomethingValid = rand(1, 100) == 22
&& $smth < time()
&& $smths > 5
&& $sxsxsx > 250
&& !$_SESSION['false'];
if ($isSometingValid) {
// do something
}
In accordance with my answer to the related
- Multiple condition IF statement
this should be refactored with Decompose Conditional, which means you should make the individual tests into separate functions. And you should get rid of the magic numbers and meaningless variable names. I would give you an example on how to do that for your code, but the code is incomprehensible.
Always indent to the enclosing statement one extra than the body of the block. You would write a function like this:
function (reallylongparam, reallylongparam, reallylongparam,
reallylongparam, reallylongparam) {
doStuff()
}
so you'd write your if statement like this:
if(rand(1, 100) == 22 && $smth < time() && $smths > 5
&& $sxsxsx > 250 && !$_SESSION['false']) {
doStuff();
}
probably
if(
rand(1, 100) == 22 &&
$smth < time() &&
$smths > 5 &&
$sxsxsx > 250 &&
!$_SESSION['false']
) {
echo "wow, big if just happened!";
}
cheers
Making your code readable is a very important aspect when it comes to supporting your code - someone else might have to do that support.
Have a look at coding styles (search around for more info if you must).
Personally I would format that snippet like so:
if (
rand(1, 100) == 22
&&
$smth < time()
&&
$smths > 5
&&
$sxsxsx > 250
&&
!$_SESSION['false']
)
{
echo "wow, big if just happened!";
}
Just encapsulate the boolean logic in a seperate function
You could also make your variable names easier to read.
精彩评论