When doing a conditional expression, it’s a smelly code pattern to then return true
or false
. Why? The conditional expression already returns a true
or false
state. Therefore, you do not need to be so verbose and hardcode a boolean return.
Here is the smelly code pattern:
<?php | |
namespace KnowTheCode; | |
add_action( 'loop_start', __NAMESPACE__ . '\code_smell_example' ); | |
function code_smell_example() { | |
if ( is_page() && ! is_user_logged_in() ) { | |
return true; | |
} | |
return false; | |
} |
Refactor this code down to one line to make it more readable. It’s less code too (skinny).
<?php | |
namespace KnowTheCode; | |
add_action( 'loop_start', __NAMESPACE__ . '\code_smell_example' ); | |
function code_smell_example() { | |
return is_page() && ! is_user_logged_in(); | |
// Or even this with the parentheses | |
return ( is_page() && ! is_user_logged_in() ); | |
} |
Strive to reduce your code and make it more simple. If you see this pattern in your code, then refactor it. Remember, you want your code to be as skinny (as few lines) as possible.
CodeTip: Reduce your code and make it more simple. Code should be as few lines as possible. Share on X
Did you learn something new? Share your thoughts.