Which style is preferable when writing this boolean expression?
Posted
by
Jeppe Stig Nielsen
on Stack Overflow
See other posts from Stack Overflow
or by Jeppe Stig Nielsen
Published on 2012-10-08T20:45:23Z
Indexed on
2012/10/08
21:37 UTC
Read the original article
Hit count: 244
I know this question is to some degree a matter of taste. I admit this is not something I don't understand, it's just something I want to hear others' opinion about.
I need to write a method that takes two arguments, a boolean and a string. The boolean is in a sense (which will be obvious shortly) redundant, but it is part of a specification that the method must take in both arguments, and must raise an exception with a specific message text if the boolean has the "wrong" value. The bool must be true
if and only if the string is not null or empty.
So here are some different styles to write (hopefully!) the same thing. Which one do you find is the most readable, and compliant with good coding practice?
// option A: Use two if, repeat throw statement and duplication of message string
public void SomeMethod(bool useName, string name)
{
if (useName && string.IsNullOrEmpty(name))
throw new SomeException("...");
if (!useName && !string.IsNullOrEmpty(name))
throw new SomeException("...");
// rest of method
}
// option B: Long expression but using only && and ||
public void SomeMethod(bool useName, string name)
{
if (useName && string.IsNullOrEmpty(name) || !useName && !string.IsNullOrEmpty(name))
throw new SomeException("...");
// rest of method
}
// option C: With == operator between booleans
public void SomeMethod(bool useName, string name)
{
if (useName == string.IsNullOrEmpty(name))
throw new SomeException("...");
// rest of method
}
// option D1: With XOR operator
public void SomeMethod(bool useName, string name)
{
if (!(useName ^ string.IsNullOrEmpty(name)))
throw new SomeException("...");
// rest of method
}
// option D2: With XOR operator
public void SomeMethod(bool useName, string name)
{
if (useName ^ !string.IsNullOrEmpty(name))
throw new SomeException("...");
// rest of method
}
Of course you're welcome to suggest other possibilities too. Message text "..."
would be something like "If 'useName' is true a name must be given, and if 'useName' is false no name is allowed".
© Stack Overflow or respective owner