7

Many times I've came across the following issue: should I use one custom controller for all the actions for some sObject or some area, or maybe there should be separate controllers for editing, inserting etc.?

I found the former approach a little bit cumbersome in salesforce, but it still seems to be more natural as I used to do so in some plain old MVC technologies like ASP.NET MVC.

I'm aware that this depends on separate cases but It would be nice to get some general principles with all the pros and cons.

8

Salesforce's MVC is much different than ASP.NET in that with Salesforce, controllers are used with VisualForce pages which relies on a View State which is limited to 135 kb. So, what to do in a particular situation greatly depends on the View State of your VisualForce page; something which can definitely be affected by your controller. A large or poorly written controller can slow down a VisualForce page and load up the View State.

The things which primarily affect the View State from a VF standpoint are going to be the DOM component tree and it's associated state. The heaviest impact on those will be the following Apex components:

  • apex input
  • apex command
  • apex action
  • apex select
  • apex in-line edit support

Any data sent to the controller through getters or returned by setters will also be held in the view state. If the data is only needed for the duration of the current page request, one will want to use the transient key word on those variables in the controller if it all possible. Otherwise, they get held in the controller and thus in the view state as well. Now, imagine a situation where you have a large controller and the same variable gets passed to a number of methods which have other variables they're assigned to which might be returned to the page. The memory required to hold the contents of the controller will increase as will the resulting view state. In such a situation, having the added functionality for re-use would not be a good thing.

That leads me to where I'm going with this. The "best practice" for fast loading VF pages would be to use controller extensions to add functionality to existing "base" controllers as needed. That would keep them as light weight as possible; particularly where view state and page load times start to become an issue.

This past Wednesday, @PBattison put on an excellent webinar on Advanced Visualforce that should be available for viewing within the coming week which I highly recommend. It covered a great deal of this material (and more) doing a far better job than I can here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.