开发者

Avoiding Multiple If's in c# - Best practise

开发者 https://www.devze.com 2023-01-22 04:37 出处:网络
Scenario: Lets say we got to check for address lines. which includes addressline1, addressline2,Town,Country,Postcode

Scenario: Lets say we got to check for address lines. which includes addressline1, addressline2,Town,Country,Postcode If a开发者_运维知识库ny 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.


private bool IsAddressValid(params string[] addressParts)
{
    return addressParts.Any(p => p != null) ? addressParts.All(p => p != null) : true;
}

To be called like so:

var addressValid = IsAddressValid(AddressLine1, AddressLine2, Town, County);


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.


If you make an array of the fields in the group, then you can do:

var fields = new object[] {AddressLine1, AddressLine2, Town, Country};
return fields.All(f => f == null) || fields.All(f => f != null);


Define this:

public static bool SameNullness(params object[] values)
{
    int nullCount = 0;
    foreach (var value in values)
    {
        if (value == null) nullCount++;
    }

    return nullCount == values.Length;
}

Then use it like:

SameNullness(AddressLine1, AddressLine2, Town, Country); 
0

精彩评论

暂无评论...
验证码 换一张
取 消