Java方法需要冷凝

时间:2015-11-08 17:56:29

标签: java

如何将此方法压缩以使其看起来更干净?它的工作原理是完美的,只是看起来非常难看,没有优雅。我确信有更好的方法可以做到这一点,我找不到它。

public class ItemProfitComparator implements Comparator<MenuItem>{
  public int compare(MenuItem menuVar1, MenuItem menuVar2) 
  {
     if( ((menuVar1.getTotalSales() - (menuVar1.getNumOrders()*menuVar1.getWholesaleCost())) - (menuVar2.getTotalSales() - (menuVar2.getNumOrders()*menuVar2.getWholesaleCost()))) > 0){
      return (int)Math.ceil(((menuVar1.getTotalSales() - (menuVar1.getNumOrders()*menuVar1.getWholesaleCost())) - (menuVar2.getTotalSales() - (menuVar2.getNumOrders()*menuVar2.getWholesaleCost()))));
     }else if(((menuVar1.getTotalSales() - (menuVar1.getNumOrders()*menuVar1.getWholesaleCost())) - (menuVar2.getTotalSales() - (menuVar2.getNumOrders()*menuVar2.getWholesaleCost()))) < 0){
      return (int)Math.floor(((menuVar1.getTotalSales() - (menuVar1.getNumOrders()*menuVar1.getWholesaleCost())) - (menuVar2.getTotalSales() - (menuVar2.getNumOrders()*menuVar2.getWholesaleCost()))));
     }else{
      return 0;
     } 
  }

}

3 个答案:

答案 0 :(得分:3)

您可以使用变量来存储计算结果:

public class ItemProfitComparator implements Comparator<MenuItem> {
    public int compare(MenuItem menuVar1, MenuItem menuVar2) {
        double res = menuVar1.getTotalSales() - (menuVar1.getNumOrders() * menuVar1.getWholesaleCost())) - (menuVar2.getTotalSales() - (menuVar2.getNumOrders() * menuVar2.getWholesaleCost()));

        if (res > 0) {
            return (int) Math.ceil(res);
        } else if (res < 0) {
            return (int) Math.floor(res);
        } else {
            return 0;
        }
    }
}

但是,对于代码审核,有一个单独的site

答案 1 :(得分:3)

正如其他人指出的那样,你可以通过使用局部变量来改善这一点。

此外,您无需使用floorceil。重要的是答案的标志。要比较两个double值,您可以

if (a > b) {
    return 1;
} else if (a < b) {
    return -1;
} else {
    return 0;
}

但是,你做得更好

return Double.compare(a, b);

请注意,Java 8引入了Comparator.comparingDouble(...)这一切。

答案 2 :(得分:1)

比较器使用lambda更容易编写:

Comparator<MenuItem> profitComparator = Comparator.comparing(
    (menuItem) -> menuItem.getTotalSales() - (menuItem.getNumOrders() * menuItem.getWholesaleCost())
);