if 异样判断尽量应用Assert
例如:
if(CollectionUtils.isEmpty(hotContents)) { log.error("社区主题获取7*24小时精选内容获取数据谬误:{}",hotContents); throw new BusinessAPIException("社区主题获取7*24小时精选内容获取数据谬误"); }
能够改为 Assert
Assert.notEmpty(hotContents, "社区主题获取7*24小时精选内容获取数据谬误");
再如:
if (CommunityConsts.TAB_NEWS_SUCCEED_STATUS.equals(tabNewResponse.getCode())) { // do somethings } else { throw new APICallException(tabNewResponse.getCode(), tabNewResponse.getMsg()); }
能够改为:
Assert.isTrue(TAB_NEWS_SUCCEED_STATUS.equals(tabNewResponse.getCode()), "7×24tab资讯举荐获取资讯接口 Fail! code: {} - msg: {}", tabNewResponse.getCode(), tabNewResponse.getMsg());
如果Assert抛出的异样不满足要求(例如要抛出个别的异样),那至多也包装一个静态方法,例如 BizAssert
。这里次要的问题是呈现了大量反复的判断语句,所以最好尽量打消这些反复代码。
异样解决不是常态
异样解决不是常态,尽量不要侵入失常业务逻辑。
例如,对返回值进行校验,之前很多代码会这样写:
if (validateUtil.checkInvalid(data)) { log.error("接口返回数据谬误:{}",data.getRemList()); throw new BusinessAPIException("接口返回数据谬误"); }
这里仅仅只是做了个异样转换,没啥养分,齐全能够封装一个新的校验办法并在外面抛出异样。封装完后写成,
validateUtil.bizCheck(data, "xxx msg");
Domain Model 尽可能封装,不要适度裸露
来看个例子,
@Data @AllArgsConstructor public class ReviewWealthFocusInfo { List<ReviewWealthFocus> reviewWealthFocus; public List<ReviewWealthFocus> getReviewWealthFocus() { if (reviewWealthFocus.size() > CommunityListConsts.FIRST_COMMUNITY_LIST) { return reviewWealthFocus.stream() .limit(3) .collect(Collectors.toList()); } return reviewWealthFocus; } }
能够看到,这个类外面,只有一个成员,而且曾经有了 getter 了,但有些同学还是习惯加上 lombok 的注解 @Data
。lombok有时候只是图个不便,其实毁坏了封装性。
能够改成这样,增加一个构造函数,外面还能够加些入参校验。并没有比lombok麻烦,IDEA有快捷键能够疾速增加 constructor, getter, setter, override 等。
public class ReviewWealthFocusInfo { private List<ReviewWealthFocus> reviewWealthFocus; public ReviewWealthFocusInfo(List<ReviewWealthFocus> reviewWealthFocus) { Validate.notNull(reviewWealthFocus); this.reviewWealthFocus = reviewWealthFocus; } public List<ReviewWealthFocus> getReviewWealthFocus() { return reviewWealthFocus.subList(0, Math.min(FIRST_COMMUNITY_LIST, reviewWealthFocus.size())); } }
上述例子还有一个有毒的中央,就是 List 的截取,棘手改了,不细说。
须要反复调用的中央,请应用循环
检视过程中,我还发现有个中央,同一个办法反复调用了两次。getTabNewsIds()
这个办法竟然反复了两次,令人非常费解。
List<String> tabNewsIds = getTabNewsIds(); List<String> otherTabNewsIds = getTabNewsIds(); ids = getTotalTabNewsId(tabNewsIds,otherTabNewsIds);
且不说这是出于何种起因要这么写,至多整个循环吧?一个简略的循环就包装起来了
private List<String> getEnoughTabNewsIds() { List<String> ids = Lists.newArrayList(); while (ids.size() <= NEWS_NUM_THRES) { ids.addAll(getTabNewsIds()); } return ids; }