Separation of concerns versus performance? - asp.net-mvc

I have an ASP.NET MVC site and I am trying to figure out separation of controller and model (repository) and HTML helper functionality.
The goal is to query a database table of photo albums information and display it grouped by year.
The steps are:
Query database and return datatable of the database information.
Convert Datatable to AlbumCollection (List)
Bucket albums by year into ALbumDictionary
Render each year in a seperate HTML table.
Given this request, I could see:
1,2,3 all in the model and the controller simply binds the View to the AlbumDictionary model
or
1,2 in the model and bind to the AlbumCollection and 3 in a HTML ViewHelper
or
1,2 in the model 3 in the controller and bind to the Albumdictionary
Thoughts?
Doing every conversion in the first loop would have the best performance but I am not sure it is the best separation of concerns.
In particular to the above question, generic feedback would be interesting: when does separation of concerns overrule performance or vise versa?

Having been a user of some truly horrendous software that I'm sure looked good from an object-oriented perspective to the designers and was even possibly easy to maintain, I want to point out that the users will come down on the side of performance almost every time.
If the performance difference is negligible, follow the separation of concerns, if it is not, do what it takes to get the best performance. We need to stop worrying as much about the extra few minutes to possibly maintain (maybe touching that code once a year once it's in prod) and more about slowness for all the users every day issue. We like to say that development time is so expensive that we need to minimize it, but the truth is that development time is often far cheaper than the amount of time we are asking our users to waste daily.

I would try to keep the Model clear of anything that has to do with rendering.
I see the grouping by year pretty close to rendering. Thats why I would not put it into Model and also not into the Controller. A common aproach is to have a Model of Poco and DAL/BLL and anonther Model called ViewModel (the Model used by the strongly typed View). This is a good place to prepare the objects for rendering.
In ViewModel I would use Linq to group the albums by years. This will hopefully be fast enough.

I would do the bucketing in the controller only if either:
the bucketing occurs just once and I can do that with one or two simple statements;
It occurs more than once but I can do that with just a AlbumDictionary.BucketByYear() statement.
Otherwise I'd use models to do that.

Related

calculated fields: to store in DB or not to store?

I am building a ruby on rails application where a user can learn words from a story (having many stories on his list of stories to learn from), and conversely, a story can belong to many users. Although the story is not owned by the user (it's owned by the author), the user can track certain personal things about each story that relate to him and only to him, such as how many words are left to learn in each of his stories (which will obviously differ from user to user).
Currently, I have a has_many :through relationship set up through a third table called users_stories. My concern/question has to do with "calculated fields": is it really necessary to store things like words_learnt_in_this_story (or conversely, words_not_yet_learnt_in_this_story) in the database? It seems to me that things like this could be calculated by simply looking at a list of all the words that the user has already learnt (present on his learnt_words_list), and then simply contrast/compare that master list with the list of words in the story in order to calculate how many words are unlearnt.
The dilemma here is that if this is the case, if all these fields can simply be calculated, then there seems to be no reason to have a separate model. If this is the case, then there should just be a join model in the middle and have it be a has_and_belongs_to_many relationship, no? Furthermore, in such a scenario, where do calculated attributes such as words_to_learn get stored? Or maybe they don't need to get stored at all, and rather just get calculated on the fly every time the user loads his homepage?
Any thoughts on this would be much appreciated! Thanks, Michael.
If you're asking "is it really necessary to store calculated values in the DB" I answer you. No, it's not necessary.
But it can give you some pros. For example if you have lots of users and the users call those values calculating a lot then it could be more winnable strategy to calculate them once in a while. It will save your server resources.
Your real question now is "What will be more effective for you? Calculate values each time or calculate them once in a while and store in DB?"
In a true relational data model you don't need to store anything that can be calculated from the existing data.
If I understand you correctly you just want to have a master word list (table) and just reference those words in a relation. That is exactly how it should be modelled in a relational database and I suggest you stick with it for consistency reason. Just make sure you set the indices right in the database.
If further down the road you run into performance issue (usually you don't) you can solve that problems then by caching/views etc.
It is not necessary to store calculated values in the DB, but if the values are often used in logic or views its good idea to store it in Database once(calculate again on change) and use from there rather then calculating in views or model.

Cascaded Comboboxes and Entity Structure

In our ASP.Net project we've got a view with 3 (or even more) cascaded combo-boxes,
The question is how should we design our (NHibernate-based) entities given that the relationship between the combo-boxes is relevant only for the sake of building the view, and given that the entire catesian product of the 3 entity types is around 2000 entities.
So the questions are actually:
Should we design the entities as a heirarchy even though the collections has no additional business value (thus making them an overhead for any other scenario)
Should the data be sent as flat rows? keeping the entities more "clean", but requires additional
coding on the view's side
Seperate to consequent requests (e.g only after combo A is selected, combo B's data is fetched from the server)? making the entire process maybe more efficient but at the cost of performance and perhaps caching?
Any thoughts?
First of all, you should not design your model (entities) by one intended UI. Today is it 3 dropdown, tommorow it can be autocomplete nad in a week some new fancy "wow" component, but your model should stay solid - it describes actual, business relations between entities, not your current UI. From this, i think it is quite obvious that you should use combination of 2 and 3.

Is there a standard model to controller 'ratio' when trying to implement good ASP.NET MVC?

I'm not sure if this question is non-sense or not, please tell me if so. I am wondering do I create my models like one per each table in my database, or do you do one per controller? Is there something I am missing here?
From what I read the Model is suppose to be a representation of the real business objects, so would I just want to make it one big model or divide them out based on things in the app? based on real user/client perception of the data?
Thanks for your advice.
There's nothing wrong with controllers sharing models. But trying to serve every controller with the same model doesn't make sense.
Models and controllers really are't related, nor should they be. Models also aren't directly related to how data is stored in your application.
Models encapsulate data. Their design should be dictated by the data they are encapsulating. The demands of the system dictate what models you'll need and what data they must hold.
Don't try to overthink it. For a given request, determine what you need to show in your view and how it will be displayed. Determine what an appropriate model would look like for this scenario. If one already exists, use it. If not, create a new model. Save the overengineering later when you know what your needs are and can find commonalities between models.
Models can also contain other models, that's fine. Think of a model for a sales report. You would have a model for the report which would contain not only a report name, a total, but also a collection of other models which make up the report's line items.
It depends on what you mean by "Model". If by model you mean the business rule layer of your application, then there is no relationship in terms of numbers. One model of that type is used for any amount of views you need to build.
Personally, however, I would not bind any view to any model, but create an intermediary layer called a ViewModel that essentially taylors the data from your model to fit a particular view. In that case, the relationship is one-to-one. This is essentially how Presenter patterns work. Every view is strongly typed to it's own ViewModel that is populated from the Model layer.
Models do not necessarily have a literal coorespondence with the database either. How you store data your model is different from how your "Model" uses that data.

The Model in MVC

I am just starting on ASP.NET MVC trying to understand the philosophy first. I think I am pretty clear on the roles played by the controller and the view but I am a little confused on the model part. Some sources say its the domain model, some say its the data model, some say its the objects that are bound to the view.
IMHO these are very different things. So please can someone clear this up once and for all?
The model is "the domain-specific representation of the information on which the application operates". It's not just the data model, as that's a lower level than the MVC pattern thinks about, but (for example) it's the classes that encapsulate the data, and let you perform processing on them.
Scott Guthrie from MS uses this definition in his announcement:
"Models" in a MVC based application
are the components of the application
that are responsible for maintaining
state. Often this state is persisted
inside a database (for example: we
might have a Product class that is
used to represent order data from the
Products table inside SQL).
Further reading:
the MVC Wikipedia article
the MVC pattern on C2
I like to actually add an additional layer to make things clearer. Basically, the "Model" is the thing that is domain specific, and knows how to persist itself (assuming persistence is part of the domain).
IMO, the other layer I referred to I call the ViewModel ... sometimes, the "model" that gets passed to the view really has nothing to do with the domain ... it will have things like validation information, user display info, lookup list values for displaying in the view.
I think that's the disconnect you're having :-)
Your sources of advice are correct when they say it is the domain model. In many instances, it will be quite closely aligned your data model as well.
Where the domain and data models differ is that the data model is relatively static in form (not content) whereas your domain model adds the specific constraints and rules of your domain. For example, in my data model (database) I represent blood pressure as smallints (systolic and diastolic). In my domain model, I have a "blood pressure reading" object that holds values for each of the two readings and that also imposes additional restrictions on the range of acceptable values (e.g. the range for systolic is much smaller than that for smallints). It also adds qualitative judgments on these values (a BP of 150/90 is "high").
The addition of these aspects of the problem domain is what makes the domain model more than just the data model. In some domains (e.g. those that would be better rendered with a fully object-oriented data model and that map poorly on the relational model) you'll find that the two diverge quite significantly. However, all the systems I've created feature a very high degree of overlap. Indeed, I often push a fair number of domain constraints into the data model itself via stored procedures, user-defined types, etc.
You should have a look at this it a step by step tutorial.
From one of the chapters: page 26
In a model-view-controller framework the term “model” refers to the objects that represent the data of
the application, as well as the corresponding domain logic that integrates validation and business rules
with it. The model is in many ways the “heart” of an MVC-based application, and as we’ll see later
fundamentally drives the behavior of it.
Hope its useful.
For example, if you're building a web site to, say, manage operations of a nuclear plant, than the model is the model of the plant, complete with properties for current operating parameters (temperature etc.), methods to start/stop power generation, etc. Mmmm... in this case the model is a actually a projection of a real plant vs. an isolated mode but you got the idea.

Best Practice for Model Design in Ruby on Rails

The RoR tutorials posit one model per table for the ORM to work.
My DB schema has some 70 tables divided conceptually into 5 groups of functionality
(eg, any given table lives in one and only one functional group, and relations between tables of different groups are minimised.)
So: should I design a model per conceptual group, or should I simply have 70 Rails models and leave the grouping 'conceptual'?
Thanks!
Most likely, you should have 70 models. You could namespace the models to have 5 namespaces, one for each group, but that can be more trouble than it's worth. More likely, you have some common functionality throughout each group. In that case, I'd make a module for each group containing its behavior, and include that in each relevant model. Even if there's no shared functionality, doing this can let you quickly query a model for its conceptual group.
I cover this in one of my large apps by just making sure that the tables/models are conceptually grouped by name (with almost 1:1 table-model relationship). Example:
events
event_types
event_groups
event_attendees
etc...
That way when I'm using TextMate or whatever, the model files are nicely grouped together by the alpha sort. I have 80 models in this app, and it works well enough to keep things organised.
You should definitely use one model per table in order to take advantage of all the ActiveRecord magic.
But you could also group your models together into namespaces using modules and sub-directories, in order to avoid having to manage 70 files in your models directory.
For example, you could have:
app/models/admin/user.rb
app/models/admin/group.rb
for models Admin::User and Admin::Group, and
app/models/publishing/article.rb
app/models/publishing/comment.rb
for Publishing::Article and Publishing::Comment
And so forth...
Without knowing more details about the nature of the seventy tables and their conceptual relations it isn't really possible to give a good answer. Are these legacy tables or have you designed this from scratch?
Are the tables related by some kind of inheritance pattern or could they be? Rails can do a limited form of inheritance. Look up Single Table Inheritance (STI).
Personally, I would put a lot of effort into avoiding working with seventy tables simply because that is an awful lot of work - seventy Models & Controllers and their 4+ views, helpers, layouts, and tests not to mention the memory load issue of keeping the design in ind. Unless of course I was getting paid by the hour and well enough to compensate for the repetition.
Before jumping in a making 70 models, please consider this question to help you decide:
Would each of your tables be considered an "object" for example a "cars" table or are some of the tables holding only relationship information, all foreign key columns for example?
In Rails only the "object" tables become models! (With some exception for specific types of associations) So it is very likely that if you have only 5 groups of functionality, you might not have 70 models. Also, if the groups of functionality you mentioned are vastly different, they may even be best suited in their own app.
There may be a small number of cases where you can use the Rails standard single-table-inheritance model. Perhaps all of the classes in one particular functional grouping have the same fields (or nearly all the same). In that case, take advantage of the DRYness STI offers. When it doesn't make sense, though, use class-per-table.
In the class-per-table version, you can't easily pull common functionality into a base class. Instead, pull it into a module. A hierarchy like the following might prove useful:
app/models/admin/base.rb - module Admin::Base, included by all other Admin::xxx
app/models/admin/user.rb - class Admin::User, includes Admin::Base
app/models/admin/group.rb - class Admin::Group, includes Admin::Base
It's already mentioned, it's hard to give decent advice without knowing your database schema etc, however, I would lean towards creating the 70+ models, (one for each of your tables.)
You may be able to get away with ditching some model, but for the cost (negliable) you may as well have them there.
You don't need to create a controller + views for each model (as answerd by srboisvert). You only need a controller for each resource (which I would expect to be a lot less than 70 - probably only 10 or 15 or so judging by your description).

Resources