principlephpMinor
Complex boolean logic vs DRY
Viewed 0 times
logicbooleandrycomplex
Problem
I have some code:
Which duplicates the line:
This is small duplication, but still duplication. I could reformat it as this:
But I feel like this drastically reduces the readability of the code.
In this type of situation, is DRY or simple more important?
$matchingEvents = [];
foreach( $this->recurringEvents as $event ){
if( $event['RCE_Type'] === 'Month' && $event['RCE_Day'] === $dayOfMonth ){
array_push( $matchingEvents, $event );
} else if( $event['RCE_Type'] === 'Week' && $event['RCE_Day'] === $dayOfWeek ){
array_push( $matchingEvents, $event );
}
}Which duplicates the line:
array_push( $matchingEvents, $event );This is small duplication, but still duplication. I could reformat it as this:
$matchingEvents = [];
foreach( $this->recurringEvents as $event ){
if( ( $event['RCE_Type'] === 'Month' && $event['RCE_Day'] === $dayOfMonth )
||
( $event['RCE_Type'] === 'Week' && $event['RCE_Day'] === $dayOfWeek ) ){
array_push( $matchingEvents, $event );
}
}But I feel like this drastically reduces the readability of the code.
In this type of situation, is DRY or simple more important?
Solution
You could move the matching test to a separate method, like this:
Then your
private function is_matching_day( $event, $dayOfWeek, $dayOfMonth ) {
if ( $event['RCE_Type'] === 'Month' && $event['RCE_Day'] === $dayOfMonth )
return true;
return $event['RCE_Type'] === 'Week' && $event['RCE_Day'] === $dayOfWeek;
}Then your
foreach statement would be more readable, and the duplicated array_push() is gone:$matchingEvents = [];
foreach( $this->recurringEvents as $event ) {
if ( $this->is_matching_day( $event, $dayOfWeek, $dayOfMonth ) )
array_push( $matchingEvents, $event );
}Code Snippets
private function is_matching_day( $event, $dayOfWeek, $dayOfMonth ) {
if ( $event['RCE_Type'] === 'Month' && $event['RCE_Day'] === $dayOfMonth )
return true;
return $event['RCE_Type'] === 'Week' && $event['RCE_Day'] === $dayOfWeek;
}$matchingEvents = [];
foreach( $this->recurringEvents as $event ) {
if ( $this->is_matching_day( $event, $dayOfWeek, $dayOfMonth ) )
array_push( $matchingEvents, $event );
}Context
StackExchange Code Review Q#48234, answer score: 5
Revisions (0)
No revisions yet.