Is it correct to use partial views for the SOLE purpose of breaking down a more complicated view into separate chunks and therefore making it more readable?
It probably seems a silly question but the reason I ask is that everything I've read about using partial views involves a piece of the UI being re-used in multiple places. In my case the piece of UI being put into the partial view is only used in one place. It is therefore done solely for readability, but I'm not sure if the performance impact of this may outweight the increased readability. Thoughts?
Whilst this is correct there are more uses.
Reusability
Ability to pass pack rendered html
from your controller so you can
append the partial view to the bottom
of containers. Great for jQuery
async calls
Seperation of concerns
Gives developers the ability to work
on different sections of a page w/out
getting in each others way.
Just to name a few.
I think that you shouldn't be worried about performance until it is a real problem, but you should be worried about your code from the first moment. I usually use partial views to simplify the logic or the structure of my views, as you are wanting to do.
Sure, that's an okay use for them. If it keeps the page organized so it's easier to maintain, I think it's fine.
Also, if I'm using caching, I find it easier to have my:
cache "this" do
# render partial
end
I find it easier to read and keep track of things, especially on an overview or dashboard page where there are lots of different parts of the pages that you're including.
I tend to be a bit more conservative. I only use a partial view when I know I'll need to reuse the code or I have multiple complex objects in ViewData that need to be displayed.
There's no right or wrong way here but I have worked on projects where there are a ton of partial views to make things "more simple" and I end up spending forever trying to track down where all the partials are (controller/action folder, shared folder, or elsewhere).
One thing about my approach though is if you have even the slightest thought that the view code may be reused down the line as the project changes use a partial. It will save a bunch of time down the road.
I veto any large and complex view in our projects. Instead, we use RenderAction to extract those pieces of code into smaller chunks/parts. I blogged about it here:
http://eduncan911.com/blog/html-renderaction-for-asp-net-mvc-1-0.aspx
Basically, you move that logic and/or parts into Controllers.
Or, if you are just talking html - then yes, breaking down a view into RenderPartials works too.
Related
I'm new to Rails and I have a question. Everyone says the preferred way of iterating through a table is to capture the data in an instance variable via a Controller, then iterate in the corresponding View.
What if I just did
<% Course.all.each do |course| %>
<!-- displays list of courses -->
<% end %>
I know using instance variables is the preferred way, but is there any reason?
Could I not use instance variables?
Yes. The code, as you've written it, works.
Using instance variables is the preferred way, but is there any reason?
It's really just an agreed design pattern to do avoid making database queries directly in the view.
A principle of MVC frameworks is to have the controller prepare all data for the view, rather than the view directly fetching data at arbitrary points. In the long term, you'll find the latter approach can become messy, un-performant and difficult to maintain.
For example, you might start making the same query multiple times, or run into N+1 problems, or struggle to test the implementation at all (because if logic is all inside the view, the only way to test might be via very complex+expensive feature tests, instead of quick and easy unit tests!) - which can make the implementation fragile and error prone.
But rules are made to be broken, and you can write code like this in rails; just take a word of warning from the past experience of developers who invented MVC frameworks in the first place: This is generally a design pattern to be avoided.
You certainly CAN do this, but it does not mean it is a good idea.
Rails operates as an MVC framework which separates models, views & controllers, which in turn is really an application of the "Separation of Concerns" design principle.
By adding controller responsibilities (fetching data) into view responsibilities (displaying data & interacting with the users), you're making it more difficult for the view code to be reused.
What if you only want to display a subset of courses but not all of them, but using the same format?
What if you want to display a different set of courses depending on who the user is at the moment?
What if you want to paginate the course list because you've got 1,000 courses already?
And so on.
This is really hard to appreciate when you are just starting out but getting into the habit as early as possible will save yourself from unlearning it later down the line.
At the end of the day, these are just conventions, and there is a time and place wherein you can break conventions but just be aware that all these "rule-breaking" might eventually come back and haunt you. That's what we call "technical debt" and as with any kind of debt, the longer you keep it, the harder it is to pay it off.
According to Brad Wilson, RenderAction is slower than RenderPartial.
However, has anyone got any statistics that show the difference in performance?
I'm in the process of developing an application where pages are composed of "Widgets".
I have two choices:
Composition at the View Level
Call RenderAction for each widget. This is by far the easiest approach but does mean that we're performing a full MVC cycle for each widget.
Composition at the Controller Level
Compose one ViewModel for the page that contains the data we need for each widget. Call RenderPartial for each widget. This is much more complicated to implement but does mean we'll make only one MVC cycle.
I tested the above approaches with 3 different widgets on a page and the difference in render time was 10ths of a second (hardly worth worrying about).
However, has anyone got any test results more concrete than this, or perhaps experience trying both approaches?
I've recently worked on an application that was experiencing performance issues, and found a view that was making four calls to RenderAction, plus another one in the layout. I found that each call to RenderAction--even when I added in a dummy action that returned an empty view--took around 200-300ms (on my local machine). Multiply by the number of calls and you have a huge performance hit on the page. In my case there were four calls causing about a second of unecessary server-side overhead. By comparison, calls to RenderPartial were around the area of 0-10ms.
I would avoid using RenderAction wherever possible in favor of RenderPartial. The controller should be responsible for returning all necessary information. In the case of widgets, if you need multiple actions for several widgets, I would try composing them into one action so the RenderAction overhead only occurs once, though if your site performs adequately I'd keep them separate for a cleaner design.
Edit: I gathered this information using MiniProfiler and hitting the site. It isn't super accurate but it does clearly show the differences.
Edit: As Oskar pointed out below, the application in question likely had some intensive code that runs for each request in global.asax. The magnitude of this hit will depend on the application code, but RenderPartial will avoid executing another MVC cycle altogether.
I'd suggest 2 more options, both require to compose the view model at Controller level and both can work together (depending on the data)
Html.DisplayFor() - display templates
Helpers via extension methods
Option 2 works very well if you want to keep those widgets in different assemblies, after all they're just functions returning a string. I think it has also the best performance, but of course you lose the 'designer friendly' templates. I think it's important to consider the maintainability aspect, not only raw performance (until you really need it, and even then, caching is more helpful).
For small stuff (date or name formatting etc) i'd use helpers, since the html is usually a span with a class, for more complex stuff I'd use the display templates.
At my new job, I was given some MVC work. There is only one controller with nine action methods(6 are for ajax rendering) . The page was bit large, so I divided it into small your controls and used render partial to render them. Some user controls were being render through ajax also. Most of the controls are not more like foreach loops and rendering some data from tables, not more 10-15 lines. The main index page passes model to all the controls. My main page looked very clean and easy to maintain.
But my team members are saying, I should put everything in the main page rather than building small controls. Their point is number of files will be a lot, if we start creating controls like this. Also they say if we are not reusing these controls somewhere else there is no point creating them separately.
I would like to know what is better approach for this kind of scenario. Any good links which can help us to understand things better, or any book we can read to clarify our questions.
Help will be appreciated.
Regards
Parminder
As a preface to my answer, let me mention the important value of maintainability. Software evolves over time... and must change to fit the need of the application.
Maintainability in code does not magically appear... Sacrifices (with a touch of paranoia sometimes) must be made in your coding style now, to have the flexibility you'd like in the future.
There may a large page in your project. Some may say that if it works, no need to fix it. But that's looking at it from a short term perspective. You may need some of those UI interfaces in other places in the future. What some persons may do (rather than make partials) is copy that code in the places where they need it - thus causing the same bloat over time that they were trying to avoid.
If you're on the project in the long haul, you'll more fully appreciate the need for flexibility over time. You can see that there are patterns that you'll want to re-use.
My suggestion then: Partials and controls are good things... they are good investments for your ease in the future. If you forecast reusability, that's a good sign for using them.
But use them sparingly. Don't micromanage everything on a page. Some things may be itching to be 'component-ized' but sometimes it's best to SSFL (Save some for later). Like everything in life, balance is important.
Having clean concise code is the way to go. Your code will be alot more readable if you utilize :
sections
templates
partial views
Just remember its always easier to navigate folder structure than to read 100's - 1000's of lines of code.
I recommend watching "Putting your controllers on a diet" by Jimmy Bogard.
Also read "Fat Controllers" by Ian Cooper.
these two links will give you a good idea on how to structure your MVC apps.
I am trying to optimize my code as much as possible. I use a lot of partial files like this:
#if (Model.PageMeta.Sidebar == PageMetaSidebar.Small) { Html.RenderPartial("_SmallSidebar"); }
..
..
..
Can someone tell me if there is a performance overhead with this. I understand that Razor views are compiled. Is it the case that when the page is displays there is another disk read to get the data for each of the partial files that I use. If that's the case then how much additional overhead could I expect with for example 5 RenderPartials on my layout page.
There will be no noticable performance hit at all here as the partials are just pulled in on the asp.net web server before streaming the resultant HTML back to the browser. This is not an expensive disk read to do and won't appear any slower than if it was a single cshtml. Obviously partials should be used if the same partial view is reused in many views. If only used in a single view then it's just a matter of clarity splitting it into a separate partials to separate parts of your model into different views.
Note you can also just use:
#Html.Partial("YourPartial")
rather than using RenderPartial. This will look in the local view folder then in shared if not found.
I don't think using RenderPartial ~5 times is going to have a significant enough impact to design your pages poorly. If it makes sense to pull the logic out (makes the page cleaner, used by multiple views, etc.) then do it. If you notice significant performance issues then you should look at them at that time, but don't prematurely optimize and create a poor design because you THINK it might slow something down.
If you like to get a better understanding of potential performance hits you might want to play around with the mvc-mini-profiler.
Please note though that I'm not advocating pre-mature optimization. However, using profiling tools might give you a better understanding of potential bottlenecks, thus helping you avoid them in the future.
In keeping with the DRY-principle I try to use partials as soon as I am repeating a particular pattern more than once or twice. As a result, some of my views consist of ten or more different partials. I am worried that this might have a negative effect on the overall performance. Some programming books compare the use of partials with the use of methods. So should I use the same rationale to determine when to use them?
What is the best practice regarding size and quantity of partials in a Rails project?
I like your practice already: Once you've repeated view code twice, refactor it out to a partial. Tim's right that you can speed it up as necessary after it's been profiled and after it's been proven necessary.
Here is my one caveat: If you work with professional designers who handle the views, it may be easier over the long term to have rather repetitive view code. Some people have a hard time searching through partials and "seeing" how they all fit together. I've found it easier with those people to let them manage the whole shebang and update more than one file if they need to. Optimal? Not to us as programmers, but designers are more often used to seeing most of the HTML in one or three files rather than 20. :)
Remember the rules of optimization!
If, once your application is complete, your views are too slow, use something like New Relic to find out where the slowdown is occurring. There are a lot of places that might be, but it's unlikely to be in your partials.