我使用spring boot开发了一个用来发送电子邮件的shell项目。
sendmail -from foo@bar.com -password foobar -subject "hello world" -to aaa@bbb.com如果缺少from和password参数,我将使用默认发件人和密码,例如noreply@bar.com和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");
}发布于 2016-01-04 15:08:13
有一种使用^ (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");
}它更具可读性,也更容易理解,而且只需要额外输入一点内容。
发布于 2016-01-04 14:59:53
好的,听起来你是想检查这两个变量的“Well”条件是否相同。您可以使用:
if ((from == null) != (password == null))
{
...
}或者使用helper变量使其更明确:
boolean gotFrom = from != null;
boolean gotPassword = password != null;
if (gotFrom != gotPassword)
{
...
}发布于 2016-01-04 19:36:51
就我个人而言,我更喜欢可读性而不是优雅。
if (from != null && password == null) {
throw new RuntimeException("-from given without -password");
}
if (from == null && password != null) {
throw new RuntimeException("-password given without -from");
}https://stackoverflow.com/questions/34586109
复制相似问题