coverage   build

Guard Clauses

A dart port of the excellent C# Guard Clauses package by Ardalis.

A simple extensible package with guard clause extensions.

A guard clause is a software pattern that simplifies complex functions by "failing fast", checking for invalid inputs up front and immediately failing if any are found.

Usage

void processOrder(Order? order)
{
    Guard.against.nullValue(order, 'order');

    // process order here
}

// OR

class Order
{
    String _name;
    int _quantity;
    double _max;
    double _unitPrice;

    Order(String name, int quantity, double max, double unitPrice) {
        _name = Guard.against.nullOrWhiteSpace(name);
        _quantity = Guard.against.negativeOrZero(quantity);
        _max = Guard.against.zero(max);
        _unitPrice = Guard.against.negative(unitPrice);
    }
}

Supported Guard Clauses

  • Guard.against.invalidInput (throws if predicate expression returns false)
  • Guard.against.invalidFormat (throws if the input string doesn't match the provided regex)
  • Guard.against.negative (throws if the input is negative)
  • Guard.against.negativeOrZero (throws if the input is negative or zero)
  • Guard.against.nullValue (throws if input is null)
  • Guard.against.nullOrEmpty (throws if string input is null or empty)
  • Guard.against.nullOrEmptyCollection (throws if the input collection is null or empty)
  • Guard.against.nullOrWhiteSpace (throws if string input is null, empty or whitespace)
  • Guard.against.nullOrInvalidInput (throws if input is null, or predicate expression returns false)
  • Guard.against.indexOutOfRange (throws if input is not a valid index)
  • Guard.against.outOfRangeItems (throws if any values in the input collection are outside the provided range)
  • Guard.against.outOfRange (throws if the input collection is outside the provided range)
  • Guard.against.zero (throws if number input is zero)

Extending with your own Guard Clauses

To extend by creating your own guard clauses, create a new extension class for Guard.

extension GuardExtensions on Guard {
  /// Throws an ArgumentError if [input] is 'foo'.
  /// Returns [input] otherwise.
  String foo(String input, {String? name}) {
    if (input.toLowerCase()) {
      throw ArgumentError.value(input, name);
    }

    return input;
  }
}

// Usage
void sumpin(String otherSumpin) {
    Guard.against.foo(otherSumpin);
    ...
}

References

The references are C#-centric but the concepts apply well.

Libraries

guard_clauses