首页 > 解决方案 > 如何通过摆脱冗余来优化下面的代码?

问题描述

我下面的代码是根据 Object Product 的一些值计算 ProductFunction。InternalProductMapper和ExternalProductMapper中的getProductFunctions方法调用ProductFunctionCalculator中的函数计算ProductFunction的值。根据我的说法,ProductFunctionCalculator 中不可能有一个函数,因为两个不同的映射器调用它。如何优化下面的代码?另外,如果我有两个函数,我不确定将另一个命名为两个不同映射器的计算函数。

public class InternalProductMapper{
  public EnumSet<ProductFunction> getProductFunctions(Product p){
     return productFunctionCalculator.get(p);
  }
}

public class ExternalProductMapper{
 public EnumSet<ProductFunction> getProductFunctions(Product p){
     return p!=null ? productFunctionCalculator.calculate(p):
                       return EnumSet.of(Function.BUSINESS,Function.MARKET);
  }
}

public class ProductFunctionCalculator{
   public EnumSet<ProductFunction> calculate(Product p){
      if(p.brand() == "ABC" && p.id.equals("1") && p.value > 100){
          return EnumSet.of(Function.BUSINESS, Function.LOCAL);
      }
   }

    public EnumSet<ProductFunction> get(Product p){
       if(p != null && p.location.equals("NY")){
            return EnumSet.of(Function.BUSINESS);
       }
       return EnumSet.of(Function.BUSINESS, Function.MARKET);
    }
}

标签: java

解决方案


“另外,如果我有两个函数,我不确定将另一个命名为两个不同映射器的计算函数。”

您可以命名一个calculateInternal和另一个calculateExternal或类似名称,除非我误解了您的意思。

您还可以在Product对象上添加一个标识符,以确定它是内部的还是外部的(可以是新字段、布尔值/枚举或其他)。您需要在初始化 Product 对象时设置此字段的值,此时您很可能知道它是什么类型的 Product。这可以允许一种新的单一计算方法,因为现在您的方法将知道如何处理不同的场景(因为您有这个新的“类型”字段),可能通过 if-else 语句,例如:

//This should not be allowed if you can help it and you should try and get 
//rid of the scenario this comes in as null - just check it before calling this method 
if(product != null) {
  if(product.isInternal()) {
    //Internal product logic
   } else {
    //External product logic
  }
}

推荐阅读