views:

94

answers:

4

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.

+6  A: 

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.

Jon Skeet
Jon, can you clarify if you should use `params object[]` or `IEnumerable<object>` as the data type for your static methods?
Kane
@Kane: I've used `params object[]` so that you can call it as `IsAnyNull(x, y, z, etc)` instead of explicitly creating a new collection.
Jon Skeet
+6  A: 

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);
Douglas
+8  A: 
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);
Dave
A: 

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); 
munificent