Conditional if more cleancode

Asked

Viewed 140 times

-1

My intention is to decrease the size of the condition, because I thought that it became extensive making it a little difficult to read, and that maybe there could be a better way to do this:

  • by checking the variables $l1 and $l2, $c1 and $c2 joints instead of separate.

  • the 4 variables $l1 and $l2, $c1 and $c2 may have any numerical value.

  • I want you to pass on condition only if:

    • $L1 and $L2 are greater than or equal to 1 and less than or equal to 8
    • and $C1 and $C2 greater than or equal to 97 and less than or equal to 104.

The condition is always the same in all situations:

  • $L1 and $L2 between 1 and 8 (including)
  • and $C1 and $C2 between 97 and 104 (including)

I have the following condition

<?php

$l1 = 1;
$l2 = 7;
$c1 = 97;
$c2 = 104;

if(
    $l1 >= 1 && $l1 <= 8 
    && $l2 >= 1 && $l2 <= 8 
    && $c1 >= 97 && $c1 <= 104 
    && $c2 >= 97 && $c2 <= 104
)
{
  // ok
}
  • As the author clarified the rules of the code, the posting was reopened and the conversation became extensive, the comments were moved to the chat - Who wants to participate, read, add or clarify something just use the link provided.

1 answer

1


I always find a good extract for functions. This helps and much in readability:

<?php

$l1 = 1;
$l2 = 7;
$c1 = 97;
$c2 = 104;

if (
    entre1E8($l1)
    && entre1E8($l2)
    && entre97e104($c1)
    && entre97e104($c2)
) {
    // ok
}

function entre1E8($a) {
    return $a >= 1 & $a <= 8;
}

function entre97e104($a) {
    return $a >= 97 && $a <= 104;
}

The names of the functions are merely illustrative, but the idea would be more or less this. It looks good in the same writing sense.

If you want to "simplify" more...

<?php

$l1 = 1;
$l2 = 7;
$c1 = 97;
$c2 = 104;

if (
    intervaloValidoL($l1, $l2)
    && intervaloValidoC($c1, $c2)
) {
    // ok
}

function intervaloValidoL($l1, $l2) {
    return entre1E8($l1) && entre1E8($l2);
}

function intervaloValidoC($c1, $c2) {
    return entre97e104($c1) && entre97e104($c2);
}

function entre1E8($a) {
    return $a >= 1 & $a <= 8;
}

function entre97e104($a) {
    return $a >= 97 && $a <= 104;
}

Here we have a good separation of responsibilities, but the price is a significant increase in the number of functions.

  • A hint, change the name merely illustrative for function between( $int , $val ), so you can take advantage of the function for other types of validations. Just pass the value that will be checked and the parameters.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.