Tuesday, September 19, 2017

Clean Code is the Documentation

1) Write code that is easy to follow and read.
   a) Keep function blocks under 20 lines. Should only do one thing.
   b) Use descriptive variable/class/method names.
   c) Try to be within 80 columns limit if possible. View code on a tablet/print out, to see if it cuts off.
2) Write your PHP Unit test before you write your code.

3) Function should have no more than three parameters! Avoid passing in arrays, as it is hard to figure out later on what you can pass to the function. Use class objects, instead:

class db_options {
  private $table_name;
....
  public function set_table_name(string $table_name): void { $this->table_name = $table_name; }
  public function get_table_name(): string {
   // IF no Database ticks are around table name then add them
    return (strrpos($this->table_name, "`") === false) ? "`{$this->table_name}`" : $this->table_name;
  }
....
}

class db {
....
  public function run(db_options $db_options) { ......... }
}

$db_options = new db_options();
$db_options->set_table_name('users');
...
$db = new db(pdo $pdo_dsn);
$db->run($db_options);
----------------------------------------------------------------------------------------------------------

4) Avoid Nested IF Statements like this:

if ($exec !== false) {
        if ( $db_options->is_read_mode() ) {
          if ( $db_options->is_fetch_all() ) {

            if (\bla_found_string($this->sql, "SQL_CALC_FOUND_ROWS")) {
              $ret = $pdostmt->fetchAll(PDO::FETCH_ASSOC);
              $fsql = "SELECT FOUND_ROWS() AS totalRows";
              $totalRows = $this->query($fsql)->fetch();
              $this->count = $totalRows[0];
              return $ret;
            } else {
              $this->count = $pdostmt->rowCount();
              return $pdostmt->fetchAll(PDO::FETCH_ASSOC);
            }
          } else {
            return $pdostmt->fetch(PDO::FETCH_ASSOC);
          }
        } elseif ( $db_options->is_write_mode() ) {
          return $pdostmt->rowCount();
        }
      }

Convert into single tabbed IF Statements, that check one condition and return control back early:
  try {
......
      if ($exec === false) {
        return false;
      }
       
      if ( $db_options->is_write_mode() ) {
        return $pdo_stmt->rowCount();
      }
       
      if ( ! $db_options->is_read_mode() ) {
        return false;
      }
     
      if ( $db_options->is_fetch_pdo_stmt() ) {
        return $pdo_stmt;
      }
     
      if ( $db_options->is_fetch_row() ) {
        return $pdo_stmt->fetch(PDO::FETCH_ASSOC);
      }
......

No comments:

Post a Comment