Alex Rivera | Logout

Is it acceptable to only use the 'else' portion of an 'if-else' statement?

Asked 2009-09-24T18:32:10.883
22

Sometimes, I feel like it is easier to check if all of the conditions are true, but then only handle the "other" situation.

I guess I sometimes feel that it is easier to know that something is valid, and assume all other cases are not valid.

For example, let's say that we only really care about when there is something wrong:

object value = GetValueFromSomeAPIOrOtherMethod();

if((value != null) && (!string.IsNullOrEmpty(value.Prop)) && (possibleValues.Contains(value.prop)))
{
    // All the conditions passed, but we don't actually do anything
}
else
{
    // Do my stuff here, like error handling
}

Or should I just change that to be:

object value = GetValueFromSomeAPIOrOtherMethod();

if((value == null) || (string.IsNullOrEmpty(value.Prop)) || (!possibleValues.Contains(value.prop)))
{
    // Do my stuff here, like error handling
}

Or (which I find ugly):

object value = GetValueFromSomeAPIOrOtherMethod();

if(!((value != null) && (!string.IsNullOrEmpty(value.Prop)) && (possibleValues.Contains(value.prop))))
{
    // Do my stuff here, like error handling
}
Edit
Report

1 Answer

28

I should preface this by saying that it's my own personal preference, but I find myself usually pulling the validation logic out of the code and into its own validate function. At that point, your code becomes much "neater" by just saying:

if(!ValidateAPIValue(value))

That, in my mind, seems a lot more concise and understandable.

answered 2009-09-24T18:38:42.973

Your Answer