LearningProcess LearningProcess - 19 days ago 5
Java Question

Java Method Needs Condensing

How can I condense this method to look more clean? It works perfect how it is, just looks extremely ugly, has no elegance. I'm sure there's a better way to go about doing this I just can't find it.

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;
}
}

}

Answer

You can use a variable to store the result of your calculation:

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;
        }
    }
}

However, for code review, there is a separate site.