php - 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。
但是如何降低复杂度呢?将它移动到另一个方法并没有帮助,因为我已经将代码移动到了一个辅助类中,并且我必须检查每个值是否已设置。这个问题在我的几个班级中以类似的方式发生。
循环遍历创建动态方法和属性名称的值数组会使其更好,还是只会降低代码的可读性?
解决方案
由于您的 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 是否会用类似的方法抱怨其他事情。
推荐阅读
- python-3.x - 如何在狮身人面像中记录“函数”类型的参数?
- python - 标记边界给定掩码
- python - Python 中的 AWS Lambda 无法导入模块
- azure - Azure 更新管理缺少更新
- javascript - 在 Firefox 中不同的值被认为是相等的
- javascript - 调用异步函数时,将回调包装在一个闭包中,该闭包将在执行原始重新进入代码之前恢复上下文
- c++ - 从 C++ 更改 QML 对象值
- nginx - Nginx Ingress 选择性反向代理位置重写
- quartz-scheduler - 石英和石英工作之间的区别
- python - 在 Pandas 中分组和删除不必要的行