C# Design – Class Design and Separation of Concerns

asp.net-mvccdesign

I'm working on an MVC application and am wondering about the best way to design one of my models.

I have a class called RightLeftPersonToggle which represents two select list boxes on the page. The user is able to move "persons" between the left and right box using buttons between them.

This class can represent both a vehicle driver or manager so the load and save code is different for each type. The class is below.

public class RightLeftPersonToggle
{
    public RightLeftPersonToggle()
    {
        LeftList = new List<Person>();
        RightList = new List<Person>();
    }

    public List<Person> LeftList { get; set; }
    public List<Person> RightList { get; set; }
    public string LeftListTitle { get; set; }
    public string RightListTitle { get; set; }
    public string PropertyName { get; set; }
}

I'm wondering what the best way to handle the loading and saving of the lists is. I've come up with two solutions but I'm not sure on which one is best.

1) The controller (or parent model) is responsible for loading and saving both LeftList and RightList. The RightLeftPersonToggle class has no knowledge of that code and remains exactly like the code above.

2) RightLeftPersonToggle gets two methods (one for save and one for load) which take functions as parameters to tell it how to do its job.

public void LoadAndFilterLists(Func<List<Person>> leftListFilter, Func<List<Person>> rightListFilter)

public void LoadSaveLists(Func<List<Person>> leftListSave, Func<List<Person>> rightListSave)

Solution number one keeps the code more simple in my opinion while solution number two seems to provide better sepration of concerns since RightLeftPersonToggle should know how to load and save itself.

Keeping in mind the fact that RightLeftPersonToggle doesn't always load and save data the same way, which of my proposed solutions would be considered best practice? Do you have any other recommendations for improvement?

Best Answer

If the logic needed to save the data differs depending on what's being shown in the lists, you should have the controller handle saving the lists. The code you've shown seems to be for your view, so all it should worry about is displaying the lists and shouldn't need to know what's actually in them. Let the controller figure out what type of data is in the 2 lists and what the appropriate save logic would be.

Related Topic