0

In order to 1. clarify possibilities on an interface and hence 2. reduce test cases plus 3. fail as fast as possible I intend to enforce validation of a model upon creation. The model shall not be created if the constellation is not valid. As a result, it is warranted to each consumer that the model provided is valid.

The solution I came up with is to have a private constructor plus a nested factory class.

But code quality rules report a design warning: CA1034: Nested types should not be visible
When to suppress warnings: Do not suppress a warning from this rule.

Are there better alternative designs for this?

public class MyValidatedModel
{
    private readonly SomeOtherModel _a;
    private readonly SomeOtherModel _b;

    // cannot be constructed elsewhere to enforce validation
    private MyValidatedModel(SomeOtherModel a, SomeOtherModel b)
    {
        _a = a;
        _b = b;
    }

    public class Factory
    {
        private readonly ImmutableList<IValidator> _validators;

        // to allow override in tests where simplification wanted
        public Factory(IEnumerable<IValidator> validators)
        {
            this._validators = validators.ToImmutableList();
        }

        public MyValidatedModel Create(SomeOtherModel a, SomeOtherModel b)
        {
            // do some validation
            if (IsValid(a, b))
            {
                // create validated model
                return new MyValidatedModel(a, b);
            }

            // do some error handling
        }
    }
}

public class Consumer
{
    public DoStuff(MyValidatedModel model)
    {
        // here we know for sure that this model is valid
    }
}
David C.
  • 48
  • 5
  • why does the create method have to have its own factory class wouldn't a static method suffice? Also why can the Isvalid equivalent code not go inside the constructor and remove the need for the create method? – ROX Nov 11 '19 at 16:19
  • Thank you for asking. I left out some bits: the constructor of the factory takes all validation rules to apply so that those can be overridden in tests. Because in some tests the overhead to create a valid model would be to much overhead. I updated the code accordingly. – David C. Nov 13 '19 at 07:42

0 Answers0