你描述聽起來很怪異的語義,肯定叫getNextItem()
沒有任何意義,除非hasItems()
是真的嗎?
無論如何,這個想法是一樣的,無論你的邏輯是如何工作的:將你的OutgoingItems
對象包裝成一個新的類,爲你檢查條件。我做了assert
的支票,但您可以選擇任何您喜歡的方式。
public class OutgoingItemsDelegate {
private final OutgoingItems items;
public OutgoingItemsDelegate(OutgoingItems items) {
this.items = items;
}
public boolean hasItems() {
return items.hasItems();
}
public Object getNextItem() {
assert !items.hasItems();
// alternatively you can do this:
// if (items.hasItems()) throw new IllegalStateException("hasItems() must not be true");
return items.getNextItems();
}
}
當然還有你可能有這個解決方案付出微小的性能和空間開銷,理想的解決方案是修復OutgoingItems
本身,而是做不到這一點,這是一個可行的選擇。
*請注意,對於要評估的assert
語句,您需要在命令行上使用-ea
標誌。