php:如何使用setter负载降低方法的圈复杂度
我有一个方法,它使用一个类的值来设置另一个类的属性:php:如何使用setter负载降低方法的圈复杂度,php,php-7.4,Php,Php 7.4,我有一个方法,它使用一个类的值来设置另一个类的属性: public static function fromDto( ProfessionArea $professionArea, ProfessionAreaDto $dto, SignatureType $signatureType ): ProfessionArea { if (null !== $dto->id) { $professionArea->setId($dto->
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抱怨说,这种方法的复杂性太高了,因为如果语句的结果是真或假,我们可能会有太多的变化。NPath当前的结果为512,不应大于200
但是如何降低复杂性?将其移动到另一个方法没有帮助,因为我已将代码移动到一个helper类中,并且必须检查每个值是否已设置。这个问题在我的几个班级中也以类似的方式出现
通过创建动态方法和属性名称的值数组进行循环会使其更好,还是只会降低代码的可读性?既然ProfessionArea对象的属性不为null似乎非常重要,我将在setters方法中对null进行检查:
职业领域{
公共功能激活($active){
如果(空!==$active){
$this->active=$active;
}
}
//这里还有其他方法
}
在这里,您展示了一个fromDto
方法来构建实例,但是假设您可以有其他类似的方法,比如fromJson
,fromString
,不管怎样,撇开圈复杂度不谈,您所展示的方法将意味着大量重复对空值的检查
<> P>在SETTER方法中,如果将CHECKD移动到NULL,可能会考虑一些业务条件(可能在某些情况下,属性为NULL是很好的),但这取决于您的要求。
也就是说,我不能说phpmd是否会用类似的方法抱怨其他问题。这是一种选择。@DisasteryJane如果你能想出一个更好的解决方案,请写一个答案,如果你愿意的话:你最初的问题非常有趣。