首页 > 解决方案 > php:如何降低具有大量设置器的方法的圈复杂度

问题描述

我有一个方法,它使用一个类的值来设置另一个类的属性:

public static function fromDto(
    ProfessionArea $professionArea,
    ProfessionAreaDto $dto,
    SignatureType $signatureType
): ProfessionArea {
    if (null !== $dto->id) {
        $professionArea->setId($dto->id);
    }
    if (null !== $dto->active) {
        $professionArea->setActive($dto->active);
    }
    if (null !== $dto->name) {
        $professionArea->setName($dto->name);
    }
    if (null !== $dto->signature) {
        $professionArea->setSignature($dto->signature);
    }
    if (null !== $dto->signatureTypeId) {
        $professionArea->setSignatureType($signatureType);
    }
    if (null !== $dto->transition) {
        $professionArea->setTransition($dto->transition);
    }
    if (null !== $dto->infotextCheck) {
        $professionArea->setInfotextCheck($dto->infotextCheck);
    }
    if (null !== $dto->textblockCompleted) {
        $professionArea->setTextblockCompleted($dto->textblockCompleted);
    }
    if (null !== $dto->deletable) {
        $professionArea->setDeletable($dto->deletable);
    }

    return $professionArea;
}

phpmd 抱怨说,这种方法的复杂性太高了,因为我们可以有太多的真假 if 语句结果的变化。NPath 当前的结果为 512,不应大于 200。

但是如何降低复杂度呢?将它移动到另一个方法并没有帮助,因为我已经将代码移动到了一个辅助类中,并且我必须检查每个值是否已设置。这个问题在我的几个班级中以类似的方式发生。

循环遍历创建动态方法和属性名称的值数组会使其更好,还是只会降低代码的可读性?

标签: phpphp-7.4

解决方案


由于您的 ProfessionArea 对象的属性不为 null 似乎非常重要,因此我将在您的 setters 方法中对 null 进行检查:

class ProfessionArea {
    public function active($active) {
        if (null !== $active) {
            $this->active= $active;
        }
    }

   //other methods here
}

在这里,您展示了fromDto一种构建实例的方法,但假设您可以使用其他类似的方法,例如fromJson, fromString, 不管和圈复杂度,您所展示的方法将意味着对所有这些针对空值的检查进行大量重复。

在 setter 方法中针对 null 移动 checkd 时可能需要考虑一些业务条件(也许在某些情况下,属性为 null 会很好),但这取决于您的要求。

也就是说,我不能说 phpmd 是否会用类似的方法抱怨其他事情。


推荐阅读