vikramjb
vikramjb

Reputation: 1365

ViewModel Redundancy Clarification

I was recently reading about ViewModel and its advantages. I am able to understand why it is needed, however the question I have is If i have two classes for the same object(ie. Person class), doesn't i make the code redundant ? Also does it no make future changes a little difficult since you need to make sure the base class model and view model has the same number of properties is that right ? For instance let's say I have table called Person which has

  1. ID
  2. Name
  3. Color

I am creating a hbm for creating the mapping for NHibernate. I have the following model class

public class Person {

 public int ID {get;set;}
 public string Name {get;set;}
 public string color {get;set;} }

If i am correct, the view model class should look like

public class PersonViewModel {

[DisplayName("Full Name")]
public string Name {get;set;}
[DisplayName("Favourite Color")]
public string color {get;set;}
}

First, I have two classess referring to the same object in the db. Even though one class is used for DB purposes and other one is used for View purposes, we still have two class with exactly the same meta data. Secondly, If I introduce a new field in the db, I would need to add it in three places, Base Model class, View Model Class and the HBM file.

Please correct me if I am wrong, how can this be termed as code optimization or a best practice.

Upvotes: 1

Views: 74

Answers (1)

devdigital
devdigital

Reputation: 34369

It depends on the approach you wish to take, you could expose the model directly as a property of your view model to avoid violating the DRY principle. However, this would violate the Law of Demeter so you would have to balance this, as your views would now be more tightly coupled with your domain model.

Also, in terms of validation, if you expose the model directly then you need to be careful that any property exposed could be set by an end user, even if you don't use the property directly in your view. You are also more likely to have different validation requirements per view, in which case validation would be the concern of the view model.

That's why the general best practice is not to expose your domain models directly to the view. You can use frameworks such as AutoMapper to reduce the data transfer plumbing code between the layers.

Upvotes: 1

Related Questions