有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何通过消除冗余来优化下面的代码?

我下面的代码是基于对象产品的一些值来计算ProductFunction。方法InternalProductMapper中的getProductFunctions和ProductFunctionCalculator中的ExternalProductMapper调用函数来计算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);
    }
}

共 (1) 个答案

  1. # 1 楼答案

    "Also, If I have two functions, i am not sure what to name the other as both calculate function for two different mappers."

    除非我误解了你的意思,否则你可以分别命名一个calculateInternal和另一个calculateExternal或类似的名称

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