When using reusable business objects, what is considered best practice when building view models?
We use an object we call Builder
to build our view models. One builder for each logical unit of views (orders, users etc), where each unit can contain a number of different view models (orders contains summary, order lines etc).
A builder may pull data through one or more standard business objects in order to build a view model.
What is considered the better practice when it comes to using business objects/models in view models?
Approach 1
Allow the use of business objects in the view model?
//Business object in some library
public class Order
{
public int OrderNum;
public int NumOrderLines;
//...
}
//Order builder in website
public class OrderBuilder
{
public OrderSummary BuildSummaryForOrder(int OrderNum)
{
Some.Business.Logic.Order obOrder = Some.Business.Logic.GetOrder(OrderNum);
//Any exception handling, additional logic, or whatever
OrderSummary obModel = new OrderSummary();
obModel.Order = obOrder;
return obModel;
}
}
//View model
public class OrderSummary
{
public Some.Business.Logic.Order Order;
//Other methods for additional logic based on the order
//and other properties
}
Approach 2
Take only the necessary data from the business objects
//Business object in some library
public class Order
{
public int OrderNum;
public int NumOrderLines;
//...
}
//Order builder in website
public class OrderBuilder
{
public OrderSummary BuildSummaryForOrder(int OrderNum)
{
Some.Business.Logic.Order obOrder = Some.Business.Logic.GetOrder(OrderNum);
//Any exception handling, additional logic, or whatever
OrderSummary obModel = new OrderSummary()
{
OrderNum = obOrder.OrderNum,
NumOrderLnes = obOrder.NumOrderLines,
}
return obModel;
}
}
//View model
public class OrderSummary
{
public int OrderNum;
public int NumOrderLines
//Other methods for additional logic based on the order
//and other properties
}
I can see the benefits and drawbacks to both, but I wonder if there's an accepted approach? In approach 1, there's no duplication of code around the models, but it creates a dependency on the business logic. In approach 2, you take only the data needed for the view, but you duplicate code around models.