降低代码的复杂性

SPI*_*984 3 java refactoring anti-patterns

我现在卡在一些非常奇怪的类中,这些类逻辑混乱了.以下是为数据库生成查询的代码示例:

if(realTraffic.getPvkp() != null) {
   //Admission point
   if(BeanUtils.isGuidEntity(realTraffic.getPvkp())) {
      findParameters +=
         " and (" + staticTableName() + ".guidPvkp = '" + realTraffic.getPvkp().getGuid()
         + "' or (" + staticTableName() + ".guidPvkpOut = '" + realTraffic.getPvkp().getGuid()
         + "' and " + staticTableName() + ".requestType = " + RequestBean.TRANSIT_TYPE
         + ")";
      if (companyType == CompanyBean.PP_TYPE && !realTraffic.isSkipOther()) {
         // TODO - add non-formed
         findParameters += " or (" + staticTableName() + ".guidPvkpOut is null "
         + " and " + staticTableName() + ".requestType = " + RequestBean.TRANSIT_TYPE
         + ")";
      }
      findParameters += ") ";
   } else {
     // Territorial department
      if(BeanUtils.isGuidEntity(realTraffic.getPvkp().getTerritorialDepartment())) {
         findParameters +=
            " and (Pvkp.guidTerritorialDepartment = '" + realTraffic.getPvkp().getTerritorialDepartment().getGuid()
            + "' or Pvkp.guidFtsDepartment = '" + realTraffic.getPvkp().getTerritorialDepartment().getGuid()
            + "' ) ";
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

这只是我在方法中进行的大量复杂检查的一部分.问题是 - 如何处理这样的代码 - 它有很多嵌套的if和check.为了使这段代码更简单,更优雅,有哪些常用方法?

UPD:我在编写新项目时理解如何避免这样的代码,但是如何处理现有的遗留代码?

gia*_*gia 7

处理这类事情的好指南来自鲍勃叔叔,称为"清洁代码".在你的情况下,我会说:

  • 将字符串连接放入方法(并使用StringBuilder)
  • 将一个转换else { if (condition) }为一个else if (condition)
  • 考虑将其companyType == CompanyBean.PP_TYPE && !realTraffic.isSkipOther()置于一个单独的方法中,因为它似乎是某种业务逻辑,如果被放入一个名为的方法中,读者可能会更清楚if (isCompanySkippedOver(companyType, realTraffic)
  • 考虑转换if(realTraffic.getPvkp() != null)

    if(realTraffic.getPvkp() == null) {return;}
    
    Run Code Online (Sandbox Code Playgroud)

减少块压痕.