There are a few suggested ways to handle primitive obsession. Personally, I would prefer:

public class Validated
{
    private string _value;
    private Regex _regex = null;

    public Validated(string pattern)
    {
        _regex = new Regex(pattern);
    }

    public bool IsValid(string value)
    {
        if (_regex.IsMatch(value))
            return true;
        return false;
    }

    public string Value
    {
        get { return _value; }
        set
        {
            if (IsValid(value))
                _value = value;
            else throw new FormatException("Invalid format.");
        }
    }
}

And use it as:

    Validated zip = new Validated(@"/^\d{5}([\-]\d{4})?$/");   
    Validated email = new Validated(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
    zip.Value = "74445";
    email.Value = "example@yahoo.com";


I can live without have a custom error message for each of my message( there's stack trace for that) and having the explicit operators.
Now if you think that this is not flexible enough to accommodate all cases, try this,

public class Validated
{
    private string _value;
    private Func<string, bool> IsValid;


    public Validated(Func<string, bool> isValid)
    {
        this.IsValid = isValid;
    }

    public string Value
    {
        get { return _value; }
        set
        {
            if (IsValid.Invoke(value))
                _value = value;
            else throw new FormatException("Invalid format.");
        }
    }
}

And use it as:

    Validated zip = new Validated((z) => new Regex(@"/^\d{5}([\-]\d{4})?$/").IsMatch(z));
        Validated email = new Validated((e) => new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$").IsMatch(e));
        zip.Value = "74445";
        email.Value = "example@yahoo.com";

 


Comments




Leave a Reply