Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A or B, not both, not neither

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.");
}
like image 779
CaffGeek Avatar asked Jul 12 '10 13:07

CaffGeek


2 Answers

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.");
like image 152
Justin Niessner Avatar answered Nov 16 '22 02:11

Justin Niessner


if (string.IsNullOrEmpty(input.A) != string.IsNullOrEmpty(input.B)) {
 // do stuff
}
like image 23
Nordic Mainframe Avatar answered Nov 16 '22 03:11

Nordic Mainframe