职责单一
一个方法只做一件事情。
eg.给员工发工资
public void pay(List<Employee> employees) {for (Employee e : employees) {if (e.isPayDay()) {Money pay = e.calculateDay();e.deliverDay(pay);}}}
实际上做了3件事:遍历所有雇员、检查是否该发工资、支付薪水
// 遍历所有雇员.
public void pay(List<Employee> employees) {for (Employee e : employees) {payIfNecessary(e);}}// 检查是否该发工资.
private void payIfNecessary(Employee e) {if (e.isPayDay()) {calculateAndDeliverDay(e);}
}// 支付薪水.
private void calculateAndDeliverDay(Employee e) {Money pay = e.calculateDay();e.deliverDay(pay);
}
优化判空
if (user != null) {Address address = user.getAddress();if (address != null) {Country country = address.getCountry();if (country != null) {String isocode = country.getIsocode();if (isocode != null) {isocode = isocode.toUpperCase();}}}
}
使用Optional改造
String isocode = Optional.ofNullable(user).map(User::getAddress).map(Address::getCountry).map(Country::getIsocode).orElse("default");
优化缓存判断
public List<Product> getProducts(List<Long> productIds) {...List<Product> products = new ArrayList<>(productIds.size());// 查询有哪些未命中的商品ID.List<Long> notHitIds = productIds.stream().filter(productId -> {String cacheKey = computeKey(productId);// 从缓存中进行查找.Result<DataEntry> result = tairManager.get(namespace, cackeKey);if (!result.isSuccess()) {log.error(String.format("tair get with key(%s) cause error:%s", cacheKey, result.getRc().getMessage()));return true;}if (ResultCode.DATANOTEXISTS.equals(result.getRc)) {return true;}Product product = result.getValue() == null ? null : result.getValue().getValue();if (product == null) {return true;}products.add(product);return false;}).collect(Collectors.toList());// 未命中缓存的商品ID从DB中查找.List<Product> productsFromDB = notHitIds.stream().map(productId -> getProductsFromDb(productId)).collect(Collectors.toList());products.addAll(productsFromDB);return products;
}