Question

I'd like to know the best practice or any suggestions for returning validation results from a service layer which is going to be used in ASP.NET MVC.

Option 1

public IEnumberable<ValidationResult> Foo(int userId, out videoId)
{
    var validationResults = new List<ValidationResult>();

    // Validation logic goes here...

    videoId = _videoService.AddVideo();

    return validationResults;
}

Option 2

public ServiceResult Foo(int userId)
{
    var validationResults = new List<ValidationResult>();
    var serviceResult = new ServiceResult();

    // Validation logic goes here...

    serviceResult.ReturnObject = _videoService.AddVideo();
    serviceResult.ValidationResults = validationResults;
    return serviceResult;
}

public class ServiceResult 
{
    public IEnumberable<ValidationResult> ValidationResults { get; set; }
    public object ReturnObject { get; set; }
}

I was currently doing option 1 because I think boxing and un-boxing in option 2 could be a pain point. Any ideas?

Was it helpful?

Solution

If return object from your service layer, you have to cast the returnobject appropriate type/value in the client code. Therefore, type checking defferred to runtime which leads invalidcastexceptions if you are not careful. More importantly it is an inelegant solution which will pollute your code and therefore reduce understandability of your code.

If you want to have only one type you could use generics:

public class ServiceResult<T>
{
    public IEnumberable<ValidationResult> ValidationResults { get; set; }
    public T ResultObject
    {
      get;set;
    }
}

If you do not like this solution, you could define a result type type for each service method.

public class ResultBase
{
    public IEnumerable<ValidationResult> ValidationResults { get; set; }

}
public class RegisterResult : ResultBase
{
    public Video Video{get;set;}
}

OTHER TIPS

I would go with option 2. It looks more cleaner. With option 2, you service becomes like a black box to the calling code. It would enable you to change the UI layer without affecting the Service layer.

Shouldn't the property 'ReturnObject' in the ServiceResult class be called 'Result' ? or in method Foo, it should be serviceResult.ReturnObject = _videoService.AddVideo();

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top