HiveBrain v1.2.0
Get Started
← Back to all entries
principlephpMinor

Complex boolean logic vs DRY

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
logicbooleandrycomplex

Problem

I have some code:

$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:

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.