Search code examples
programming-languagesc#-3.0

Avoiding Multiple If's in c# - Best practise


Scenario: Lets say we got to check for address lines. which includes addressline1, addressline2,Town,Country,Postcode If any one of the property is entered, all other fields are mandatory. If none of it is entered, the validation doesnt have to get trigged.

To achieve it, I ended up with two lines of If statement. Like

if(AddressLine1 != null || AddressLine2 != null || Town != null || Country != null)
{
    if(AddressLine1 != null && AddressLine2 != null && Town != null && Country != null) == false
     {
          return false;
     }   
}

Note: I am using c#. Are there any language constructs i can make use of.


Solution

  • Well, the null-coalescing operator can help with the first:

    if (AddressLine1 ?? AddressLine2 ?? Town ?? Country != null)
    {
        if (AddressLine1 == null || AddressLine2 == null ||
            Town == null || Country == null)
        {
            return false;
        }
        // Presumably there's more here
    }
    

    You might want to write some helper methods though:

    if (IsAnyNonNull(AddressLine1, AddressLine2, Town, Country))
    {
        if (IsAnyNull(AddressLine1, AddressLine2, Town, Country))
        {
            return false;
        }
    }
    

    Where the utility methods would be something like:

    public static bool IsAnyNonNull(params object[] values)
    {
        return values.Any(x => x != null);
    }
    
    public static bool IsAnyNull(params object[] values)
    {
        return values.Any(x => x == null);
    }
    

    Of course, you've still got two if statements - but I think that's basically necessary here anyway.