DRY vs Security and Maintainability with MVC and View Models - asp.net-mvc

I like to strive for DRY, and obviously it's not always possible. However, I have to scratch my head over a concept that seems pretty common in MVC, that of the "View Model".
The View Model is designed to only pass the minimum amount of information to the view, for both security, maintainability, and testing concerns. I get that. It makes sense.
However, from a DRY perspective, a View Model is simply duplicating data you already have. The View Model may be temporary, and used only as a DTO, but you're basically maintaing two different versions of the same model which seems to violate the DRY principal.
Do View Models violate DRY? Are they a necessary evil? Do they do more good than bad?

This has been brought up time and time again. Not only is it a pretty substantial dupe but the answer is subjective and argumentative. ViewModels are a response to DDD and the concept of persistence ignorance.
To say not using ViewModels is bad means ignoring that Django and Rails and most PHP ORM/MVC frameworks don't care at all about those concepts. Do you want somebody to tell you all those other languages and frameworks are "doing it wrong?".
Whether or not you want to use ViewModels is 100% dependent on what architecture styles you are going for and what the goals of the application are.
This is like asking is dragging and dropping GridViews in a WebForm app appropriate? Depends on a lot of things.
There is also a misconception about DRY that you have here. Do Proxy classes from a WCF service violate DRY? Does the ViewModel contain logic? The primary goal of DRY is to not have duplicated logic with a meaningful purpose. Do a couple of DTOs that share object shapres violate that?
The DDD principal of bounded contexts would make for a good read too. If a ShoppingCart object needs to function differently in a warehouse vs ecommerce website setting does that mean you to share the types? What happens when the only shared functionality is totaling a price ( price + tax + shipping )? Do you create a base class just for that therefore increasing coupling? What are the tradeoffs in time/cost/maintenance for being 100% DRY for a simple method like GetTotal(). Does violating DRY when it makes sense actually decreasing the complexity and overall cost of maintaining your codebase?
I'm sorry for answering with so many questions but hopefully now you can see the nuances and intricacies of the question you asked. ;)

One could also note that not using view models would be a violation of the single responsibility principle -- your entity should not be polluted with UI concerns.
I also think the real value of view models doesn't necessarily become apparent in version 1.0 of your application. You will thank yourself when working on version 2.0 when you completely re-think how your back-end works but you don't have to carry those changes out to the view layer.

Related

MV4 Application with EF5 model first, without ViewModels or Repositories

I'm building a MVC4 app, I've used EF5 model first, and kept it pretty simple. This isn't going to a huge application, there will only ever be 4 or 5 people on it at once and all users will be authenticated before being able to access any part of the application, it's very simply a place order - dispatcher sees order - dispatcher compeletes order sort of application.
Basically my question is do I need to be worrying about repositories and ViewModels if the size and scope of my application is so small. Any view that is strongly typed to a domain entity is using all of the properties within that entity. I'm using TryOrUpdateModel in my controllers and have read some things saying this can cause a lot of problems, but not a lot of information on exactly what those problems can be. I don't want to use an incredibly complicated pattern for a very simple app.
Hopefully I've given enough detail, if anyone wants to see my code just ask, I'm really at a roadblock here though, and could really use some advice from the community. Thanks so much!
ViewModels: Yes
I only see bad points when passing an EF Entities directly to a view:
You need to do manual whitelisting or blacklisting to prevent over-posting and mass assignment
It becomes very easy to accidentally lazy load extra data from your view, resulting in select N+1 problems
In my personal opinion, a model should closely resembly the information displayed on the view and in most cases (except for basic CRUD stuff), a view contains information from more than one Entity
Repositories: No
The Entity Framework DbContext already is an implementation of the Repository and Unit of Work patterns. If you want everything to be testable, just test against a separate database. If you want to make things loosely coupled, there are ways to do that with EF without using repositories too. To be honest, I really don't understand the popularity of custom repositories.
In my experience, the requirements on a software solution tend to evolve over time well beyond the initial requirement set.
By following architectural best practices now, you will be much better able to accommodate changes to the solution over its entire lifetime.
The Respository pattern and ViewModels are both powerful, and not very difficult or time consuming to implement. I would suggest using them even for small projects.
Yes, you still want to use a repository and view models. Both of these tools allow you to place code in one place instead of all over the place and will save you time. More than likely, it will save you copy paste errors too.
Moreover, having these tools in place will allow you to make expansions to the system easier in the future, instead of having to pour through all of the code which will have poor readability.
Separating your concerns will lead to less code overall, a more efficient system, and smaller controllers / code sections. View models and a repository are not heavily intrusive to implement. It is not like you are going to implement a controller factory or dependency injection.

What is Loosely Coupled Code?

I recently learned Ruby and Rails, I come across these terminologies, that I can't understand off the bat.
So Please explain, ( with analogies, if possible ) what is Loosely coupled Code.
A Lay Man's Explanation,
You have two classes, Class A and Class B that probably interact together. if they are loosely coupled, Class A would do what it is supposed to Do(what you want it to do) without knowing the details of Class B's Implementation
Hope it makes some Sense?
loose coupling basically means that you want the components of your program to connect easily with other components, this was you can enjoy code reuse and make things more efficient, e.g., there are Design Patters like MVC (Model View Controller) that help you with separation of concerns, you can have some of your code responsible for the GUI and some other code responsible for the access to a database, and if you want to change any of these parts you want them to avoid being too dependent on each other, i.e., that's why you should rely on interfaces instead of implementations, you want to make things easier because software is always changing/evolving.
Usually loose coupling is mentioned along with the concept of "High Cohesion", this one can be subjective but it's nothing more than writing code that makes sense and design your components in a way that will facilitate understanding, maintenance, extensibility etc.

Do we use Rails ActiveRecord as a Hybrid Structure, i.e. Data Structure+Object?

I have been using Rails for over 4 years so obviously I like Rails and like doing things the Rails Way and sometimes I unknowingly fall to the dark side.
I recently picked up Clean Code by Uncle Bob. I am on Chapter 6 and a bit confused whether we as rails developers break the very fundamental rule of OO design, i.e. Law of Demeter or encapsulation? The Law of Demeter states that an object should not know the innards of another object and it should not invoke methods on objects that are returned by a method because when you do that then it suggests one object knows too much about the other object.
But very often we call methods on another object from a model. For example, when we have a relationship like 'An order belongs to a user'. Then very often we end up doing order.user.name or to prevent it from looking like a train wreck we set up a delegate to do order.name.
Isn't that still like breaking the Law of Demeter or encapsulation ?
The other question is: is ActiveRecord just a Data Structure or Data Transfer Object that interfaces with the database?
If yes, then don't we create a Hybrid Structure, i.e. half object and half data structure by putting our business rules in ActiveRecord Models?
Rails is Rails. What else is there to say. Yes, some of the idioms in Rails violate good design principles. But we tolerate this because it's the Rails way.
Having said that, there is far too much model usage in most rails applications. Far too often I see view code directly accessing models. I see business rules folded into the active record object. A better approach would be to isolate the business rules from the active records and isolate the views from the models. This wouldn't violate any rails idioms, and would make rails applications a lot more flexible and maintainable.
IMHO if you follow the purist approach too much then you end up in a mess like Java where it uses all the right design patterns but no-one can remember the eight lines of code you need just to open a file and read its contents.
Rails' ActiveRecord framework is an implementation of Martin Fowler's Active Record design pattern. Active Records in Rails are certainly not just dumb data structures or DTOs because they have behaviour: they perform validation, they can tell you if their attributes have changed etc. and you're free and indeed encouraged, to add your own business logic in there.
Rails in general encourages good practice e.g. MVC and syntactic vinegar to make doing bad things difficult and/or ugly.
Yes, ActiveRecord deliberately breaks encapsulation. This is not so much a limitation of Rails as it is a limitation of the pattern it's based on. Martin Fowler, whose definition of ActiveRecord was pretty much the template Rails used, says as much in the ActiveRecord chapter of POEAA:
Another argument against Active
Record is the fact that it couples
the object design to the database
design. This makes it more difficult
to refactor either design as a project
goes forward.
This is a common criticism of Rails from other frameworks. Fowler himself says ActiveRecord is mainly to be used
...for domain logic that isn't too
complex...if your business logic is
complex, you'll soon want to use your
object's direct relationships,
collections, inheritance and so forth.
These don't map easily onto Active Record.
Fowler goes on to say that for more serious applications with complex domain logic the Data Mapper pattern, which does a better job of separating the layers, is preferable. This is one of the reasons that Rails upcoming move to Merb has been generally seen as a positive move for Rails, as Merb makes use of the DataMapper pattern in addition to ActiveRecord.
I'm not sure Demeter is the primary concern with ActiveRecord. Rather I think breaking encapsulation between the data and domain layers breaks Uncle Bob's Single Responsibility Principle. Demeter I think is more a specific example of how to follow the Open/Closed Principle. But I think the broader idea behind all these is the same: classes should do one thing and be robust against future changes, which to some degree ActiveRecord is not.
Concerning "Law of Demeter" one thing I've not seen mentioned is the concept of distance. By that I mean, "How closely related are the object involved?" It is my opinion that this would make some difference whether I care to follow "Law of Demeter" or not.
In the case of ActiveRecord, the objects involved in most of the LoD violations are inseparably bound together into a close relationship. Changing the internal data structure of these objects require a change in the database to reflect that new structure. The tables of a database are typically "bound" together into a single database, which even reflects these "associations" through foreign key constraints (or at least contain primary & foreign keys).
So I don't generally concern myself with following LoD between my AR objects. I know that they are tightly bound to each other due to their very nature.
On the other hand I would be more concerned about LoD between more distant objects, especially those that cross MVC boundaries or any other such design device.

Should mvc web applications be 3 tier?

I will designing a couple of web applications shortly. They will probably be done in asp.net mvc.
In my existing web apps, done in delphi, the data access layer is seperated out into a completely separate application, sometimes running on a different server. This is done more for code reuse than for architectuaral reasons. This won't be a factor in the next app as it will be all new.
Is having a separate data access application overkill in a mvc app? I will already be separating out the business classes by virtue of using MVC, and I will be using an ORM to do the db persistance.
Edit: Just to clarify; I use the term tier to refer to separate physical applications, something more than just a logical separation or layer.
The term "Tier" in my experience is generally referring to physical application seperations e.g. Client Tier & Server Tier.
MVC - refers to 3 "Layers" with the concern being separation around the 3 concerns it details Model (Data), View (UI), Controller (App Logic).
Now that I have made that distinction regarding my terminology..
Is having a separate data access application overkill in a mvc app?
I would say No(again depending what you mean by application), it is not overkill, as it may in actual fact result in a more maintainable system. Your ORM will possibly allow for new data access options to be plugged in, but what if you wish to add a new ORM? Having a clearly separated Data Access Layer (DAL) will allows for much greater future flexibility in this aspect of your application.
On the other hand, depending on the scale and vision for the application creating a completely stand alone Data Access option may be overkill, but in a nutshell separation of the DAL into different assemblies is very much a recommended practice in the composition of an application implementing the MVC pattern.
Hope this helps, If you need more depth do comment.
Well I gues it depends a little on whether you're talking about tiers (pysical) or layers (logical/projects).
Regarding the layering - you could take a look at something like s#arp architecture (code.google.com/p/sharp-architecture/ ) for an example of how they do it (they have taken a pretty maximal approach to layering).
For an example of more minimalistic views here, take a look at Ayende's blog: ayende.com/Blog/
Regarding tiers - I think needlessly adding extra tiers and putting everthing over the wire will just hit your performance, unless you need to do this for capacity reasons. Get the layers right, and them seperate them into teirs as you need to adjust for capacity (should not take too much refactoring if you've seperated your concerns well).
Great comment Tobias.
I say add enough layers so that it makes sense to you and makes it easier to maintain. Also to keep a seperation of concerns.

My ASP.NET MVC application is Anemic

I read Fowlers description of Anemic Domain and I believe I have those symptoms. I have several objects doing nothing but passing data around in different packages. I also have several Services that pretty much handle all the behavior (executive functioning). I am starting to lose track of why and what i did and where to find certain tasks.
The application does what I want, but i wonder if i just have a procedural program in oo disguise. Perhaps I can never shake my procedural programming past? should I?
In MVC, Should I eliminate my services and spread that responsibility to my Controllers and Model Objects?
I appreciate analogies between MVC concepts and DDD conepts...
I think controllers should be relatively thin. Their job is mainly being taking the request, delegating it to the appropriate application services and determining the correct action result.
If you're feeling that your domain entities are overly anemic I would suggest going over your Services and determine whether that functionality belongs on an Entity instead. I found this was my biggest problem starting with DDD was that I would push all behavior to Services rather than critically thinking about whether this was something more appropriate on the Entity.
Why don't you try the Evans book as suggested in one of your previous questions?

Resources