开发者

Paranoid: avoiding code duplication in/after loops

开发者 https://www.devze.com 2023-02-01 04:34 出处:网络
I\'ve got a bit strange question on code duplication. There are lots of loops like this: $prev_name = null;

I've got a bit strange question on code duplication. There are lots of loops like this:

    $prev_name = null;
    $clone = null;

    while($row = mysql_fetch_assoc($res)){
      if($prev_name != $row['req']){    
        if($prev_name){
          while($clone <= $end){            
            echo '<td>-</td>';              
            $clone->step();
          }
          echo '</tr>';
        }
        echo '<tr><td>' . htmlspecialchars($prev_name = $row['req']) . '</td>';                                                                                                                                    
 开发者_如何学运维       $clone = clone $start;        
      }

      $rowdate = date_create($row['date']);
      while($clone < $rowdate){         
        echo '<td>-</td>';
        $clone->step();
      }

      echo '<td>' . $row[$field] . '</td>';
      $clone->step();
    }

    if($prev_name){
      while($clone <= $end){
        echo '<td>-</td>';
        $clone->step();
      }
      echo '</tr>';
    }

as you see if() after loop is the same as 2-nd if() in loop. is it possible to reduce this kind of duplication?


Put it in a function.

 function writeSteps($prev_name,$clone,$end)
 {
    if($prev_name){
      while($clone <= $end){            
        echo '<td>-</td>';              
        $clone->step();
      }
 }


Sure. Extract Method is your friend.

Just put this code into a method and call it from both places.

if($prev_name){
  while($clone <= $end){            
    echo '<td>-</td>';              
    $clone->step();
  }
  echo '</tr>';
}
0

精彩评论

暂无评论...
验证码 换一张
取 消