Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am still hesitating to use ViewModels instead of a Model for the View

Wether I use Automapper or manually mapping, that plays no role.

All the data for a ReleaseViewModel must be first in the Release because it is filled in the data access layer with it. 90% of my model are like this. Why the overhead of duplicating everything?

What about the KISS principle and over-engineering?

Of course every tool for its appropriate task, but very often I read on SO that not using ViewModels in asp.net mvc is a NO-GO.

Where to draw the line? Should I use ViewModels when they differentiate to 50 %, 75% or 99% from my models ?

I have a model Release:

 public class Release
    {      
        public int Id { get; set; }       
        public string Name { get; set; }
        public string Author { get; set; }
        public DateTime CreatedAt { get; set; }
        public int FailedTestsCount { get; set; }
        public int SucceededTestsCount { get; set; }
        public int SumTestsCount
        {
            get
            {
                return SucceededTestsCount + FailedTestsCount;
            }
        }
        public int SumTestingTime { get; set; }
    }

a viewmodel ReleaseViewModel:

public class ReleaseViewModel
{
    [HiddenInput(DisplayValue = false)]
    public int Id { get; set; }

    [Required(ErrorMessage = "Name must not be empty.")]
    [StringLength(30, ErrorMessage = "Enter max. 30 chars for a name.")]
    [Remote("ReleaseExists", "Release", ErrorMessage = "This name already exists.")]
    public string Name { get; set; }    
    public string Author { get; set; }    
    public DateTime CreatedAt { get; set; }    
    public int FailedTestsCount { get; set; }    
    public int SucceededTestsCount { get; set; }    
    public int SumTestsCount 
    {
        get
        {
            return SucceededTestsCount + FailedTestsCount;
        }
    }

    public int SumTestingTime { get; set; }
}
like image 539
Pascal Avatar asked Jun 26 '12 19:06

Pascal


People also ask

What is the difference between model and ViewModel?

A model is usually more closely related to how your data is stored (database, services, etc.) and the model will closely resemble those. The ViewModel on the other hand is closely related to how your data is presented to the user. It is usually a flatten version of your model, denormalized, etc.

Should I use ViewModels?

The ViewModel is essential when you want a separation of concerns between your DomainModel (DataModel) and the rest of your code.

Why do we use ViewModels?

The ViewModel class is designed to hold and manage UI-related data in a life-cycle conscious way. This allows data to survive configuration changes such as screen rotations. ViewModels separate UI implementation from your app's data.

Should each view have its own ViewModel?

It is not necessary for any view to have a view model to function. However, Google recommends the pattern because it leads to good design. If you want to say that your app is MVVM, then you need to keep the view separated from the data that drives it.


2 Answers

ViewModel is something which is for the VIEW. most of the time it is similar to your entity model. But not always.

Look at your example. In your ViewModel, you have the Remote Attribute and some Validation attributes. So this Remote Name checking is something you add to give a better user experience to your User. It is specific to the View.

Another scenario you need a Viewmodel is for screens where you have more than one models involved. Ex : You have a User Entity and a Project Entity and you want to provide a screen where a Project can be added to a User. So in this case, you can create a viewmodel to handle that

public class ProjectToUserVM
{
  public int UserId { set;get;}
  public string UserName { set;get;}  // i want to display only name of user!
  public int ProjectID { set;get;}
  public IEnumerable<SelectListItem> Projects { set;get}
}

Do not use ViewModels for all your Model Entities. Create it when your VIEW really need it. I use my Model entity objects directly in some views without create a viewmodel sometimes because those are exactly same. Ex : Country / State/ City ( Look up table data.No Add/Edit)

like image 56
Shyju Avatar answered Sep 28 '22 05:09

Shyju


Why the overhead of duplicating everything?

First of all, you might think I am duplicating the code, but the fact is that you are not, in case you are doing it, you have a serious design problem

I have found there's one principle that when you do not follow it, it is truly the root of all evil: the SRP (Single Responsibility Principle)

Perhaps because you have not found the problem yet, or perhaps, you have and you just have patched your code. The responsibility of your domain object is totally different to the responsibility to present the data to the user.

A model in MVC, should be a class representing all the data the view needs to render and nothing more. You need to populate this model with data from your domain. (or in a CQRS architecture, from your query services)

If you follow a CQRS architecture (the basics at least, you do not need to implement event sourcing nor use a service bus in order to separate your commands from your queries), this will be clearer to you, the responsibility of a query object is completely different from a command object (an action from your domain)

I think you have misunderstood the KISS principle, while it speaks about over-engineering your code or the YAGNI, that doesn't mean you have to reuse everything in your application

Believe me, I learnt this the bad way =(, the only code that should be reused is the infrastructure code, when talking about domain code, it's better to follow always the SRP

like image 42
Jupaol Avatar answered Sep 28 '22 05:09

Jupaol