PHPackages                             awjudd/guard-clauses - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. awjudd/guard-clauses

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

awjudd/guard-clauses
====================

A simple package with guard clause helpers.

0.5.0(1y ago)01.4k↓29.3%[1 PRs](https://github.com/awjudd/guard-clauses/pulls)MITPHPCI passing

Since Jun 20Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/awjudd/guard-clauses)[ Packagist](https://packagist.org/packages/awjudd/guard-clauses)[ RSS](/packages/awjudd-guard-clauses/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (5)Dependencies (2)Versions (7)Used By (0)

Guard Clauses
=============

[](#guard-clauses)

A [guard clause](https://deviq.com/design-patterns/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.

Sample Usage
------------

[](#sample-usage)

Avoiding Primative Obsession:

```
use JuddDev\GuardClauses\Guards\Numeric\IntegerGuard;

class PositiveInteger
{
    public function __construct(int $value)
    {
        IntegerGuard::isPositiveOrZero($value);
    }
}
```

By doing this, you are then able to quickly make sure your objects are valid upon creation.

You can also use it in methods:

```
use JuddDev\GuardClauses\Guards\Numeric\IntegerGuard;

class BankAccount
{
    public function __construct(private int $balance)
    {
    }

    public function withdraw(int $amount): bool
    {
        IntegerGuard::isPositiveOrZero($amount);

        // Logic to remove
    }
}
```

Why is this better? It reduces the overall nesting required in your code. While the below is a simple problem, you can see how it can propagate.

```
use JuddDev\GuardClauses\Guards\Numeric\IntegerGuard;

class BankAccount
{
    public function __construct(private int $balance)
    {
    }

    public function withdraw(int $amount): bool
    {
        if($amount
