awjudd/guard-clauses

一个包含守卫子句辅助器的简单包。

0.3.0 2024-06-22 16:56 UTC

This package is auto-updated.

Last update: 2024-09-22 17:26:19 UTC


README

守卫子句是一种通过“快速失败”简化复杂函数的软件模式,它在前端检查无效输入,如果发现任何无效输入,则立即失败。

示例用法

避免原始执着

use JuddDev\GuardClauses\Guards\Numeric\IntegerGuard;

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

通过这样做,您可以快速确保在创建对象时对象是有效的。

您还可以将其用于方法中

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
    }
}

为什么这样做更好?它减少了您代码中所需的总体嵌套。虽然下面是一个简单的问题,但您可以看到它如何传播。

use JuddDev\GuardClauses\Guards\Numeric\IntegerGuard;

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

    public function withdraw(int $amount): bool
    {
        if($amount <= 0) {
            return false;
        }

        // Logic to remove
    }
}