language-agnostic - A 或 B,不是两者,都不是

标签 language-agnostic if-statement xor coding-style

自从阅读 Clean Code 以来,我一直在努力使我的代码具有描述性且易于理解。我有一个条件,必须填写 A 或 B。但不能同时填写。也不是。目前if检查这种情况的语句很难一目了然。你会怎么写下面的内容,让你一目了然地看清正在​​检查什么

if ((!string.IsNullOrEmpty(input.A) && !string.IsNullOrEmpty(input.B)) 
    || string.IsNullOrEmpty(input.A) && string.IsNullOrEmpty(input.B))
{
    throw new ArgumentException("Exactly one A *OR* B is required.");
}

最佳答案

异或的时间:

if(!(string.IsNullOrEmpty(input.A) != string.IsNullOrEmpty(input.B)))
    throw new ArgumentException("Exactly one A *OR* B is required.");

你也可以看到它写成:
if(!(string.IsNullOrEmpty(input.A) ^ string.IsNullOrEmpty(input.B)))
    throw new ArgumentException("Exactly one A *OR* B is required.");

关于language-agnostic - A 或 B,不是两者,都不是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3229115/

相关文章:

algorithm - 选择随机元素的数据结构?

language-agnostic - 是否有任何模式或是否有任何用于继承数据/对象的标准术语?

javascript - 我将如何结合这两个相似的功能?

c++ - 如何或或异或和内存块

c - C 中 float 组的异或加密

language-agnostic - 适用于小型个人项目的最佳可移植开发平台

algorithm - 关于使用什么方法/数据结构/算法的建议

c++ - 如何构建从叶子到根的二叉树

java - 通过 ID 分配两个数组

algorithm - 嵌套 if 与 and 条件