我想知道在我需要从中选择第一项的列表上进行前置条件检查的最佳模式是什么。
换句话说,我认为列表不应该是null
,它的大小应该> 1。
我发现 Guava 的 checkPositionIndex 在这方面没有帮助。相反,我发现它违反直觉,请参阅下面的示例,因为我使用 checkPositionIndex 而不是 checkArgument,如未触发的守卫之后所述,该示例在空列表上进行了轰炸。
即使我从中获取 .get(0) ,检查位置 0 似乎也不足以验证参数?
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import java.util.List;
import com.google.common.collect.Lists;
public class HowShouldIUseCheckPositionIndex {
private static class ThingAMajig {
private String description;
private ThingAMajig(String description) {
this.description = description;
}
@Override
public String toString() {
return description;
}
}
private static void goByFirstItemOfTheseAMajigs(List<ThingAMajig> things) {
checkNotNull(things);
// Check whether getting the first item is fine
checkPositionIndex(0, things.size()); // Looks intuitive but...
System.out.println(things.get(0)); // Finally, help the economy!
checkArgument(things.size() > 0); // This would have worked :(
}
public static void main(String[] args) {
List<ThingAMajig> fullList =
Lists.newArrayList(new ThingAMajig(
"that thingy for the furnace I have been holding off buying"));
List<ThingAMajig> emptyList = Lists.newLinkedList();
goByFirstItemOfTheseAMajigs(fullList);
// goByFirstItemOfTheseAMajigs(emptyList); // This *bombs*
}
}