According to the improving - refactoring existing code to Java code to the PHP code / * * * * * * * * * * I copy of the variable name is * * * * * * * * * * * * /Copy the code

Refining function 1

After the reconstruction


  $post_name = $_POST['name'];
  if(isSetOrEmpty($post_name)) {
    .
  }
  $post_age = $_POST['age'];
  if(isSetOrEmpty($post_age)) {
    .
  }


  function isSetOrEmpty($value) {
    if(isset($value) && !empty($value)) {
      return true;
    }else{
      return false;
    }
  }Copy the code

The original code

  function printOwing() {
    //print banner
    echo '**************************<br/>';
    echo 'Banner<br>';
    echo '**************************<br/>';
    //print details
    echo 'name:Lili';
    echo 'amount:'.getOutstanding();
  }Copy the code

Inline the function

If the logic of a function is too simple, cancel the function by moving the code in it to the code calling itCopy the code

After the reconstruction

  function getRating() {
    return ($number > 5)?2 : 1;
  }Copy the code

The original code

  $price = $order['price'];
  return $price > 1000; Copy the code

Introduce explanatory variables

After the reconstruction

  $isLogin = $_SESSION['is_login'] > =1;
  $isLine = $_SESSION['is_line'] > =1;
  $isAdmin = $admin > 0;
  if($isLogin && $isLine && addLoginHistory() && $isAdmin) {
      .
  }Copy the code

The original code

  $temp = 2*($height + $width);
    echo $temp;

    $temp = $height + $width;
    echo $temp;Copy the code

Replace nested conditional statements with guard statements

After the reconstruction

Statements following return will not be executedCopy the code
  function getPayAmount() {
        if($isDead) {
            return deadAmount();
        }
        if($isSeparated) {
            return separatedAmount();
        }
        if($isRetired) {
            return retiredAmount();
        }

        return normalPayAmount();
    }Copy the code

To be continued……