LightController's ValidateInput method should be pure #149
Description
This method should do what its name tells us: validate input data. Instead, it stores the validation result within a backing field:
This method is not idempotent as it has side effects.
Let's take this view model as an example:
public class TestVM : LightViewModel<TestVM>
{
public string Id { get; set; }
public override void Validate()
{
RuleFor(i => i.Id).NotEmpty().WithErrorCode("ERR_ID_REQUIRED");
}
}
If we'd mistakenly call ValidateInput
twice, we'd end up with THREE error messages. Why is that? The method calls the view model's Validate
method:
which builds validators for the view model itself. By calling it multiple times, each RuleFor
would also be applied multiple times. So, calling twice is the same as doing this:
public override void Validate()
{
RuleFor(i => i.Id).NotEmpty().WithErrorCode("ERR_ID_REQUIRED");
RuleFor(i => i.Id).NotEmpty().WithErrorCode("ERR_ID_REQUIRED");
}
Combine this with the fact that we reuse the list of errors, and now we have three error messages.
And this problem grows exponentially. ValidateInput
should be a pure function.
Also, the method Factory<T>
throws the InvalidInputException
but, in my opinion, this is the responsability of the ValidateInput
method.