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

Performing multiple validation checks

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

Problem

I have a validation which checks that a string is a valid asset number. There are currently three formats it could be in, like: 001-123456, WSH002M52B, or CTR0025MLD. The way my code is set up now is like:

public bool IsValidAssetNum(string assetNum)
{
    if (this.IsNorthAmericanAssetFormat(assetNum)) return true;
    if (this.IsGermanAssetFormat(assetNum)) return true;
    if (this.IsAustralianAssetFormat(assetNum)) return true;

    return false;
}


With each of those checks being like:

private bool IsNorthAmericanAssetFormat(string assetNum)
{
    var regex = new Regex(ComponentsResources.NorthAmericaAssetNumValidationRegex);
    var match = regex.Match(assetNum);

    return match.Success;
}


In the future, if more formats come up, we'll have to add a new specific format check as well as add it to the IsValidAssetNum function. Is there a pattern out there to solve this issue? I know a lot of if statement refactorings come from the command pattern or strategy pattern, but this seems like a different type of issue.

Solution

Regular expressions, when compiled down, are very high performing. I would suggest that you build a composite expression, let the Regex engine optimize it, and have just a single check... something like:

string[] validators = {ComponentsResources.NorthAmericaAssetNumValidationRegex, ....};
var compoundValidator = new Regex("(" + string.join(")|(", validators) + ")");


Then, in your code, you can reuse that single regex just once:

public bool IsValidAssetNum(string assetNum)
{
    return compoundValidator.Match(assetNum).Success;
}


There are any number of ways you can add validators to the the system, config files come to mind as being an easy way to manage them without code changes.

Code Snippets

string[] validators = {ComponentsResources.NorthAmericaAssetNumValidationRegex, ....};
var compoundValidator = new Regex("(" + string.join(")|(", validators) + ")");
public bool IsValidAssetNum(string assetNum)
{
    return compoundValidator.Match(assetNum).Success;
}

Context

StackExchange Code Review Q#90740, answer score: 7

Revisions (0)

No revisions yet.