C# – Should an MVP/MVC Model contain behaviour

asp.net-mvccdesign-patternsdomain-driven-designmvp

I have read plenty of questions on here, which appear to confuse the MVP/MVC Model with the Domain Model. In my mind the MVP Model calls the Service, which then calls a rich Domain Model i.e. the MVC/MVP model is a view model..

I have seen a lot of code, which does this (this is the MVC Model):

public class Model : IModel
{
    private IService service;

    public PersonModel GetPerson(int id)
    {
        PersonDTO personDTO = service.GetPerson(int id);
        PersonModel personModel = Mapper.Map<PersonModel>(personDTO);
        return personModel;
    }
}

The model calls the service and the service calls a rich domain model i.e. a domain model where the classes contain both state and behaviour.

Notice in the above code that there is a class called Model (which contains behaviour and calls the service) and a class called PersonModel. Should there be one class called PersonModel, which contains both state and behaviour if a rich Domain Model is by the business layer/domain layer? I am talking about best practice here. I know both approaches work.

Best Answer

From an mvc perspective the two separate classes in your example is desirable over a single class. This gives you proper separation of concerns which helps your code be maintained more easily. If your PersonModel contained Service in it then you would exposing that to the view which is against the mvc pattern, if it had a non-functioning Service so you are isolating the view from data access then you have a partially functioning object which is probably worse and will cause headaches. Furthermore, by having the separate classes you give PersonModel only one reason to change, which is what a person is has changed. Service is also unaffected by changes to what a person is as its only concerned with how to get that person. Keeping this separation helps keep you business layer from leaking into your model and duplicating logic or coupling them to the point they can't be cleanly separated any more.

Related Topic