I have an ASP.NET MVC site, that uses a CommandService. This command service is responsible for executing the commands, but before they are executed each command needs to be validated, so there’s a Validate operation that returns a ValidationResult, that looks like (simplified):
public class ValidationResult
{
public List<string> ErrorCodes { get; set; }
}
I would like to improve this, because currently a list of strings is returned, like ‘UserDoesNotExist’ or ‘TitleIsMandatory’, and this is not the best approach of course.
It would be better to return something strongly typed. But how can I do that?
Option 1: use one big enum like:
public enum ErrorCode { UserDoesNotExist, TitleIsMandatory}
public class ValidationResult
{
public List<ErrorCode> ErrorCodes { get; set; }
}
I don’t know if it’s a good idea to create such a big enum and put all domain error codes in it?
Option 2: use classes
public class ErrorCode {}
public class UserDoesNotExist : ErrorCode {}
public class TitleIsMandatory : ErrorCode {}
public class ValidationResult
{
public List<ErrorCode> ErrorCodes { get; set; }
}
Is cleaner, but harder to use?
What would you do, or did I miss other options?
So this is the way I solved it. First, the main ValidationResult class looks like:
ValidationResultItem is an abstract class:
and there are two implementations of it:
and
Each command handler has its own implementation of BusinessValidationResultItem, for example:
This means that if the client gets a ValidationResult, he can cast the BusinessValidationResultItem to the concrete AddArticleBusinessValidationResultItem and so use the specific enumeration in a switch statement – avoiding magic strings.