在 Java 8 方式中检查对象中包含的空对象和空值

2022-09-04 06:52:21

如何用Optimals重写这个函数,使其更加Java 8?还是我应该保持原样?

public void setMemory(ArrayList<Integer> memory) {
    if (memory == null)
        throw new IllegalArgumentException("ERROR: memory object can't be null.");
    if (memory.contains(null))
        throw new IllegalArgumentException("ERROR: memory object can't contain null value.");

    this.memory = memory;
}

答案 1

你有一个可以移动到方法的模式:condition -> throw an exception

private void checkOrElseThrow(boolean condition, Supplier<? extends RuntimeException> exceptionSupplier) {
    if (condition) {
        throw exceptionSupplier.get();
    }
}

public void setMemory(List<Integer> memory) {

    checkOrElseThrow(memory == null, () -> new IllegalArgumentException("message #1"));
    checkOrElseThrow(memory.contains(null), () -> new IllegalArgumentException("message #2"));

    this.memory = memory;
}

如果异常的类型不会更改,则仅传递异常的消息是合理的(感谢@tobias_k指出它):

private void checkOrElseThrow(boolean condition, String exceptionMessage) {
    if (condition) {
        throw new IllegalArgumentException(exceptionMessage);
    }
}

public void setMemory(List<Integer> memory) {

    checkOrElseThrow(memory == null, "message #1");
    checkOrElseThrow(memory.contains(null), "message #2");

    this.memory = memory;
}

答案 2

如果你想坚持下去,并且你在类路径上有番石榴,你可以使用这个:IllegalArgumentException

Preconditions.checkArgument(memory != null, 
            "ERROR: memory object can't be null.");
Preconditions.checkArgument(!memory.contains(null), 
            "ERROR: memory object can't contain null value.");

您不能在这里真正使用,因为您希望针对不同的条件使用不同的错误消息。Optional

另一方面,如果您没有问题,只有一条错误消息,则可以执行以下操作:

this.memory = Optional.ofNullable(memory)
            .filter(x -> !x.contains(null))
            .orElseThrow(() -> new IllegalArgumentException(
                         "memory object is null or contains null values"));

推荐