自从阅读 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/