Where class conversion methods go

Many of my classes need function conversions.

  • DataRow → Object Converters
  • ViewModel ↔ Model Converters

My question is where should 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 the converter

public class EmployeeModelViewModelConverter
{
  public static EmployeeViewModel ConvertToViewModel(Employee) {}
}
var vm = new EmployeeModelViewModelConverter.ConvertToViewModel(myEmployee);

Option 3 is perhaps the cleanest because it has tons of converter classes, as well as tons of static functions or tons of IOC initialization / injection. It also has the ugliest syntax, or you need to add another class using extensions.

: ViewModel/Model, , . , .

+3
4

, №3, .

EDIT: , , . @kyoryu ViewModel, , ViewModel, .

+3

, , 2. ViewModel " " , , -, ViewModel.

1 ( ), Model ViewModel ( - ViewModels, , ).

3 , , . , , ViewModel .

+1

, - AutoMapper. DTO ViewModel, .

+1
source

This may be one of those situations related to personal preferences. Each of your options is implemented in the .NET library, so we can guess that there is no clear best practice from Microsoft's point of view:

  • someCollection.ToArray ()
  • DateTime.Parse ()
  • Convert.ToInt32 ()
0
source

Source: https://habr.com/ru/post/1759184/


All Articles