Guard Statements

5 minutes or less on guard statements. Go!

Description

Like an if statement, guard executes statements based on a Boolean value of an expression. Unlike an if statement, guard statements only run if the conditions are not met. You can think of guard more like an Assert, but rather than crashing, you can gracefully exit.

-Source: ecerney via http://ericcerney.com/swift-guard-statement/

Show me the code!(Before)

W3schools Tutorial on if/else


function greetUser() {
    var greeting;
    var time = new Date().getHours();
    if (time < 10) {
        greeting = "Good morning";
    } else if (time < 20) {
        greeting = "Good day";
    } else {
        greeting = "Good evening";
    }
    return greeting;
}
					

Refactor


function greetUser() {
    var time = new Date().getHours();
    if (time < 10) {
        return "Good morning";
    } else if (time < 20) {
        return "Good day";
    } else {
        return "Good evening";
    }
}
					

Gaurd!


function greetUser() {
  var time = new Date().getHours();
  if(time >= 20) return "Good evening";
  if(time < 10) return "Good morning";
  return "Good day";
}
					

Not just Javascript: PHP


namespace App\Presenters;
use Carbon\Carbon;
class SamplePresenter extends Presenter{

  public function formatPlanDate($dateKey){
    return $this->formatDate($this->entity[$dateKey]);
  }

  private function formatDate($date){
    if(empty($date)) return '';

    $formatteddate = new Carbon($date);
    return $formatteddate->format('m/d/Y');
  }
}
					

Not just Javascript: Ruby


module API
  class Client
    ...
    def process_payload(payload, &block)
      return [] if payload.empty?
      block.call
    end
  end
end
					

Questions?