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
}
}