Many of my classes end up needing convert functions.
- DataRow -> Object converters
- ViewModel <-> Model Converters
My question is where should the functions live?
Option 1: Inside the source class
public class Employee
{
public EmployeeViewModel ToViewModel() {}
}
var vm = myEmployee.ToViewModel()
Option 2: Inside the destination class
public class EmployeeViewModel
{
public static EmployeeViewMOdel FromModel() {}
}
var vm = EmployeeViewModel.FromModel(myEmployee);
Option 3: Inside a converter
public class EmployeeModelViewModelConverter
{
public static EmployeeViewModel ConvertToViewModel(Employee) {}
}
var vm = new EmployeeModelViewModelConverter.ConvertToViewModel(myEmployee);
Option 3 seems to be the cleanest at the cost of having tons of converter classes laying around and either tons of static functions or tons of initialization/IOC injection. It also has the ugliest syntax or you have to add yet another class using extensions.
Clarification: I'm not talking just about the ViewModel/Model classes, but anything where you need to convert one class to another. As another example, I have a rendering system where objects often need to be converted to renderable primitives.