HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Determining if all strings are parsable to int

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
determiningparsableallareintstrings

Problem

I have to loop through a list of strings and validate that all are parsable to int and not less than 1. Also, if a string is not parsable but is null or whitespace, then it is OK and my validator should not fail.

Here's the code I have come up with which works fine but leads to method complexity:

public static bool ArePerPersonBILimitsInvalid(IEnumerable bilimits)
        {
            return bilimits.Any(c =>
            {
                int d;
                if (!int.TryParse(c, out d))
                {
                    if (string.IsNullOrWhiteSpace(c))
                    {
                        return false;
                    }

                       return true;
                }

                if (d < 1)
                {
                    return true;
                }

                return false;
            });
        }

Solution

I find that negatives in method names lead to confusing code. For instance,

if (!ArePerPersonBILimitsInvalid(...))



"Are there no BI limits that are invalid?"

becomes much more readable when we write it this way:

if (ArePerPersonBILimitsValid(...))



"Are all BI limits valid?"

So let's fill in the blanks.

public static bool ArePerPersonBILimitsValid(IEnumerable biLimits)
{
    return biLimits.All(IsBILimitValid);
}


Great, so now we need to write IsBILimitValid.

public static bool IsBILimitValid(string biLimit)
{
    if (string.IsNullOrWhiteSpace(biLimit))
    {
        return true;
    }

    int value;
    return int.TryParse(biLimit, out value) && value >= 1;
}


This way the code much more closely reflects your problem statement:


loop through a list of strings and validate that all are parsable to
int and not less than 1

Code Snippets

if (!ArePerPersonBILimitsInvalid(...))
if (ArePerPersonBILimitsValid(...))
public static bool ArePerPersonBILimitsValid(IEnumerable<string> biLimits)
{
    return biLimits.All(IsBILimitValid);
}
public static bool IsBILimitValid(string biLimit)
{
    if (string.IsNullOrWhiteSpace(biLimit))
    {
        return true;
    }

    int value;
    return int.TryParse(biLimit, out value) && value >= 1;
}

Context

StackExchange Code Review Q#59468, answer score: 19

Revisions (0)

No revisions yet.