How to write long IF more beautifully?

I have a 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"?

+4
source share
9 answers

According to my answer to the related

this needs to be reorganized using the Decompose Conditional , which means you have to make separate tests separate functions. And you have to get rid of magic numbers and meaningless variable names. I would give you an example of how to do this for your code, but the code is incomprehensible.

+3
source

I prefer to split before boolean operators.

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

I like to name my conditions and group them so that they understand 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 } 
+6
source
 $isSomethingValid = rand(1, 100) == 22 && $smth < time() && $smths > 5 && $sxsxsx > 250 && !$_SESSION['false']; if ($isSometingValid) { // do something } 
+5
source

Always retreat to the attached statement for one additional than the body of the block. You should write a function like this:

 function (reallylongparam, reallylongparam, reallylongparam, reallylongparam, reallylongparam) { doStuff() } 

therefore, you should write your if statement as follows:

 if(rand(1, 100) == 22 && $smth < time() && $smths > 5 && $sxsxsx > 250 && !$_SESSION['false']) { doStuff(); } 
+2
source

probably,

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

amuses

0
source

Creating your code for reading is a very important aspect when it comes to supporting your code - someone may need this support.

Check out the coding styles (find more information if you need to).

Personally, I would format this snippet like this:

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

Just encapsulate the logic in a separate function

0
source

You can also simplify reading variable names.

0
source

Source: https://habr.com/ru/post/1345083/


All Articles