问题
Given the following:
bool isCorrect = theAnswer == 42;
Which is the preferred way of testing false boolean logic in C# (programming in general)?
if (!isCorrect)
// throw exception
or
if (isCorrect == false)
// throw exception
The reason I ask is because one of our senior developers at work suggests we should always use the latter approach as it enhances readability and ensures other developers can clearly see the false check; an exclamation mark is easy to miss. I much prefer the former as it's more concise and readable enough to me.
I understand that this may be a subjective issue so was wondering if there was a concrete preference mentioned in any coding style.
回答1:
I have seen production code from senior developers containing such code:
if (isCorrect.ToString().Length == 5)
But I'm still using:
if (!isCorrect)
Use what you think is more readable for you, there is no statistics among all developers))
回答2:
The preferred way (I'm not sure if it actually is a best practice, but it definitely should be) is to not test false
// First question: "Is the answer correct ?"
bool isCorrect = theAnswer == 42;
// Second question: "What if it is ?"
if (isCorrect)
{
}
else //Third question: "What if it isn't ?"
{
}
It's not only more logical, but saves you from scrolling around to skip error handling if you need to follow the actual flow of your code.
Also, it's worth pointing out for completeness that boolean names should always be positive: think isCorrect VS isNotWrong ... isPositive VS isNotNegative ... much easier not only to read but to understand too.
回答3:
Given the following:
bool isCorrect = theAnswer == 42;
The clearest way to check the inverse is (IMHO!):
bool isWrong = !isCorrect;
...
if (isWrong)
// throw exception
回答4:
You are right that (!condition) is more concise.
The senior dev is right that (condition == false) is more 'visible' (or readable if you like).
Since it just boils down to preference, you should just do what the senior dev suggests and keep everything consistent whether you like it or not. When you are the senior dev you can go back and change everything.
来源:https://stackoverflow.com/questions/13763386/what-is-the-preferred-coding-style-for-checking-if-something-is-false