I was just writing an if statement with fairly long property names and came occross this problem.
Let say we have an if statement like this:
if(_someViewModelNameThatIsLong.AnotherPropertyINeedToCheck == someValue &&
!_someViewModelNameThatIsLong.ThisIsABooleanPropertyThatIsImportant)
{
//Do something
}
The second property is of a boolean type and it makes no sense to have the stetement like
if(boleanValue == true)
Is there a better way to emphasize the negation then to put the !
in front. To me it seems like this can easily be overseen when reading the code and may potentialy cause problems with debuging
5
if(_someViewModelNameThatIsLong.NeedsMeToDoSomething(someValue))
{
//Do something
}
And then, in the view model object
public bool NeedsMeToDoSomething(string someValue)
{
return AnotherPropertyINeedToCheck == someValue &&
!ThisIsABooleanPropertyThatIsImportant;
}
(assuming someValue is a string and isn’t known by the model object)
This not only emphasises the ! operator, but it makes it more readable generally. Now, in the calling method, I can see one condition, which should be well-named to describe the condition in the context of the calling object. And in the model object, I can see what that means in the context of the model object.
4
Put it in its own if block prior to evaluating the less important conditions. Not only would it be easier to read without the clutter of the other conditions, but it’s also the first condition a programmer will read. Combine this with the idea already mentioned by @scrwtp to assign to a variable with a meaningful name and you get:
var isValid = !_someViewModelNameThatIsLong.ThisIsABooleanPropertyThatIsImportant;
if( isValid )
{
if( _someViewModelNameThatIsLong.AnotherPropertyINeedToCheck == someValue )
{
//Do something
}
}
If you’re programming in a compiler language, most times these nested if blocks get combined in the end anyway, so long as you don’t insert code between the outer if and the inner if, so it shouldn’t affect performance in these cases.
If you are using C/C++ then the preprocessor could provide readability.
#define NOT !
if(_someViewModelNameThatIsLong.AnotherPropertyINeedToCheck == someValue &&
NOT _someViewModelNameThatIsLong.ThisIsABooleanPropertyThatIsImportant)
{
//Do something
}
2
I’d just extract
`!_someViewModelNameThatIsLong.ThisIsABooleanPropertyThatIsImportant`
In a Method that returns this. If you name this method NotThisIsABooleanPropertyThatIsImportant
you should be fine.