Rules

Secret ingredients to quality software

Edit
Info

Do you use Thin controllers, Fat models and Dumb views?

Created on 18 Jul 2012 | Last updated by Adam Stephensen on 02 Nov 2012 07:10 AM (over 8 years ago)

Thin Controllers

You need to think of a controller as more of a coordinator than a controller. It is responsible for calling the business layer and passing from the business layer to the view. It is also responsible for process flow.

public ActionResult Details(decimal todaysWeather) { var todaysWeatherInFarhenheit = ((9.0 / 5.0) * todaysWeather) + 32; return View(todaysWeatherInFarhenheit); } Figure: Business logic is mixed up within the controller making it fatter than it should be public ActionResult Index() { var todaysWeather = weatherDB.Today.ToList(); return View(todaysWeather); } Figure: The controller is co-ordinating between the business layer and the view public ActionResult Details(int? id) { if (!id.HasValue) return RedirectToAction("Index");

return View(); } Figure: The controller is co-ordinating process flow (directing traffic)

Dumb Views

Views shouldn't have any flow logic, application logic or business rules. The only logic you should have in the view is in relation to the displaying of data. The view should never go out and get information from somewhere else. @{ var theMonth = DateTime.Now.Month; } <p>The numeric value of the current month: @theMonth</p>

@{ var outsidetempinfahrenheit = ((9.0 / 5.0) * model.outsideTemp) + 32; var weatherMessage = "Hello, it is " + outsidetempinfahrenheit + " degrees."; } <p>Today's weather: @weatherMessage</p> Figure: Business logic is mixed in with the view @{ var theMonth = DateTime.Now.Month; } <p>The numeric value of the current month: @theMonth</p>

@{ var weatherMessage = "Hello, it is " + model.outsideTemp + " degrees."; } <p>Today's weather: @weatherMessage</p> Figure: The logic is related to the displaying of data only

Fat Model

So where do we put all the logic? The answer of course is in the model, hence the name fat model.

Adam CoganAdam Cogan

We open source. This page is on GitHub