2 回答
TA贡献1821条经验 获得超4个赞
下面的代码并没有像减少语句数量那样最小化代码,但它也消除了不必要的变量:
if(object.getIsDayDependent()) {
List<Double> prices = Arrays.asList(object.getSundayPrice(),
object.getMondayPrice(),
object.getTuesdayPrice(),
object.getWednesdayPrice(),
object.getThursdayPrice(),
object.getFridayPrice(),
object.getSaturdayPrice());
object.setDayDependent(IntStream.range(0, 7)
.mapToObj(i -> new DayPrice(i, prices.get(i)))
.collect(Collectors.toCollection(LinkedList<Double>::new)));
} else {
object.setPrice(null);
object.setDayDependent(new LinkedList<>());
}
TA贡献1780条经验 获得超5个赞
在不修改关联类(产品类)作为挑战的情况下,我为此拥有的最短代码是这样的:
if(object.getIsDayDependent())) {
Double priceDay0 = object.getSundayPrice();
Double priceDay1 = object.getMondayPrice();
Double priceDay2 = object.getTuesdayPrice();
Double priceDay3 = object.getWednesdayPrice();
Double priceDay4 = object.getThursdayPrice();
Double priceDay5 = object.getFridayPrice();
Double priceDay6 = object.getSaturdayPrice();
object.setDayDependent(new LinkedList<>(Arrays.asList(
new DayPrice(0, priceDay0),
new DayPrice(1, priceDay1),
new DayPrice(2, priceDay2),
new DayPrice(3, priceDay3),
new DayPrice(4, priceDay4),
new DayPrice(5, priceDay5),
new DayPrice(6, priceDay6))));
}
不多,但也许有人可以回答一些更聪明的方法。
添加回答
举报