Ever since reading Clean Code I have been trying to keep my code descriptive and easy to understand. I have a condition where either A or B must be filled in. But not both. And not neither. Currently the if
statement to check for this condition is hard to follow at a glance. How would you write the following to make it clear at a glance what is being checked
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.");
}
Time for an XOR:
if(!(string.IsNullOrEmpty(input.A) != string.IsNullOrEmpty(input.B)))
throw new ArgumentException("Exactly one A *OR* B is required.");
You may also see it written as:
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)) {
// do stuff
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With