/** * 最后给个例子说明契约式编程的的简洁 */ /** * 防御式编程 */ public Integer get(Integer percent, List counts){ if(percent == null || counts == null){ return null; } if(counts.size() == 0){ return null; } if(percent < 0){ throw new RuntimeException(); } int sum=0; for (Integer count : counts) { if(count != null){ sum += count; } } return sum; } /** * 契约式编程 * * @param percent percent 必须大于0,否则抛出异常 * @param counts @NotEmpty注解提示调用方先判断size() > 0 * NoneNulList保证了容器中的元素不可能为null,将这判空这个过程前移到数据产生时 * @return */ public Integer get2(Integer percent, @NotEmpty NoneNulList counts){ // 业务相关的校验还是由本函数完成 if(percent < 0){ throw new RuntimeException(); } int sum=0; for (Integer count : counts) { sum += count; } return sum; }