使用Java 8函数而不是多个If ELS



我的代码下方,getbrand和colculatesum是返回值的某些函数。我想使用Java 8函数压实此代码。如果可能的话,我想摆脱多个。是否可以使用Java 8功能?

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class Q56068628 {
    static class Brand {
        public Set<Location> locations() { return Collections.emptySet(); }
    }
    static class Location {}
    static class Product {}
    int getSum(int price, Product p){
        int sum = 0;
        if(price > 0){
           Brand b = getBrand(p); // getBrand takes type Product as argument
           if( b !=null){
              Set<Location> s = new HashSet<>();
              s.addAll(b.locations());
              for(Location l : s){
                sum = calculateSum(l, sum); /* calculateSum function takes location
                            argument and calculates sum. Sum value is replaced for
                          each for loop call */
              }
           }
        }
       return sum;
    }
    private Brand getBrand(Product p ){
    //// some code returns brand
        return null;
    }
     private int calculateSum(Location l, int sum ){
        //// some code returns an integer
        return 0;
     }
}

可能是,但是if语句通常比方法调用便宜,而且对于不知道这些API的人来说,更容易阅读。您可以考虑的一个改进是:

private Optional<Brand> getBrand(Product p ){
   //...
   //something...
   if (condition) { return Optional.ofNullable(new Brand(p)); }
   else { return Optional.empty(); }
}

然后:

Optional<Brand> brand = getBrand(p);
if (brand.isPresent()) {
  Brand b = brand.get();
}

零处理上的更安全。

最新更新