Poor logic
November 21st, 2008
No comments
Golden tidbit I found while doing some maintenance:
$count = count($some_array);
if($count)
{
if($count > 1)
{
$val = 'PluralText';
}
elseif ($count == 1)
{
$val = 'SingularText';
}
elseif ($language == 'fr')
{
$val = 'PluralText';
}
else
{
$val = 'SingularText';
}
}
else
{
$val = 'None found';
}
could have been just written as
if ( $count = count( $some_array ) )
{
$val = ( $count > 1 ) ? 'PluralText' : 'SingularText';
}
else
{
$val = 'None found';
}
The reason in this example, the first section language code would never be reached.
The program would never reach the “$language” if condition. Allowing us to remove that extra code.
Simplifying the code to the point where it’s easily readable. Some may say that ternary statements are cryptic to read. I agree for the most poart. But when setting a simple value… say setting up initial values.
$value =
(empty($this->getRequestParameter('some_random_parameter'))
?
null
:
$this->getRequestParameter('some_random_parameter');
is better then writing
if (!empty($this->getRequestParameter('some_random_parameter'))
{
$value = $this->getRequestParameter('some_random_parameter');
}
else
{
$value = null;
}