代码改造实录--缩小分支范围,使读码更直观
原来的代码:
if (date == null) { measured = this.measuredRepository.findByUserIdAndTypeAndCodeAndDate(userId, type, code, DateUtils.getToday()); } else { measured = this.measuredRepository.findByUserIdAndTypeAndCodeAndDate(userId, type, code, date); }
修改后的代码:
Measure measured = this.measuredRepository.findByUserIdAndTypeAndCodeAndDate(userId, type, code, date == null ? DateUtils.getToday() : date);
也可以改为:
if (date == null) { date = DateUtils.getToday(); } Measure measured = this.measuredRepository.findByUserIdAndTypeAndCodeAndDate(userId, type, code, date);
总之,既然两个分支都是调用同一个方法,只是对其中某个参数的处理上有差别,那就把分支限定在对该参数的处理上。这样可以更直观的看出分支的不同来。