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.

4 Answers 4

8
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);
Sign up to request clarification or add additional context in comments.

Comments

6

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.

2 Comments

Jon, can you clarify if you should use params object[] or IEnumerable<object> as the data type for your static methods?
@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.
6

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.