java - 如何通过摆脱冗余来优化下面的代码?
问题描述
我下面的代码是根据 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);
}
}
解决方案
“另外,如果我有两个函数,我不确定将另一个命名为两个不同映射器的计算函数。”
您可以命名一个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
}
}
推荐阅读
- firebase - 如何将结果值从 firestore 保存到变量中,并将其用于 Vue 中的各种组件和状态
- c# - 在 UWP 项目中使用 CollectionView 的 Xamarin Forms 4(pre 4)问题
- mysql - MySQL查询以计算最近日期的重复次数
- c++ - 构建 c++ 插件时出错,解决方案是什么?
- clustered-index - 雪花:2 个相关列具有非常不同的聚类信息(一个完美,另一个糟糕)
- python - 加速截图功能 - Python
- cocoa - 当 NSWindow 的标题栏在全屏模式下可见时如何获得通知?
- android - 选择应用程序打开文件
- idris - 函数类型的类型列表
- javascript - 如何使用 JavaScript/CSS 制作圆形 ScrollBox?