小编典典

检查 Java 中的两个参数,要么都不为空,要么都优雅地为空

all

我用spring boot开发了一个用来发邮件的shell项目,例如

sendmail -from foo@bar.com -password  foobar -subject "hello world"  -to aaa@bbb.com

如果缺少fromandpassword参数,我使用默认的发件人和密码,例如noreply@bar.comand 123456

因此,如果用户传递from参数,他们也必须传递password参数,反之亦然。也就是说,要么两者都不为空,要么都为空。

我如何优雅地检查这个?

现在我的方法是

if ((from != null && password == null) || (from == null && password != null)) {
    throw new RuntimeException("from and password either both exist or both not exist");
}

阅读 62

收藏
2022-08-27

共1个答案

小编典典

有一种使用^( XOR ) 运算符的方法:

if (from == null ^ password == null) {
    // Use RuntimeException if you need to
    throw new IllegalArgumentException("message");
}

if如果只有一个变量为空,则条件为真。

但我认为通常最好使用if具有不同异常消息的两个条件。您无法使用单个条件定义出了什么问题。

if ((from == null) && (password != null)) {
    throw new IllegalArgumentException("If from is null, password must be null");
}
if ((from != null) && (password == null)) {
    throw new IllegalArgumentException("If from is not null, password must not be null");
}

它更具可读性并且更容易理解,并且只需要额外输入一点点。

2022-08-27