good_evening
good_evening

Reputation: 21759

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"?

Upvotes: 4

Views: 2503

Answers (9)

coder1
coder1

Reputation: 3525

You could also make your variable names easier to read.

Upvotes: 0

pauljwilliams
pauljwilliams

Reputation: 19225

Just encapsulate the boolean logic in a seperate function

Upvotes: 0

Gordon
Gordon

Reputation: 317139

In accordance with my answer to the related

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.

Upvotes: 3

Travis Webb
Travis Webb

Reputation: 15018

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();
}

Upvotes: 2

Francesco Terenzani
Francesco Terenzani

Reputation: 1391

$isSomethingValid = rand(1, 100) == 22
   && $smth < time()
   && $smths > 5
   && $sxsxsx > 250
   && !$_SESSION['false'];

if ($isSometingValid) {
    // do something
}

Upvotes: 5

Ian Wood
Ian Wood

Reputation: 6573

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!";
}

Upvotes: 0

Dominik Kukacka
Dominik Kukacka

Reputation: 567

probably

if(
    rand(1, 100) == 22 && 
    $smth < time() && 
    $smths > 5 && 
    $sxsxsx > 250 && 
    !$_SESSION['false']
) {
    echo "wow, big if just happened!";
}

cheers

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190986

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
}

Upvotes: 6

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799150

I prefer breaking before the boolean operators.

if(rand(1, 100) == 22
   && $smth < time()
   && $smths > 5
   && $sxsxsx > 250
   && !$_SESSION['false']
)

Upvotes: 18

Related Questions