Debian Codegraph @

www/src/content/essays/mvc.md

raw symbols SCIP
1 ---
2 title: "Model/View/Controller (MVC)"
3 description: "Carson Gross give an introduction to the Model/View/Controller (MVC) 01-frontend pattern and its relevance to modern web development. He explores MVC concepts, its historical adoption in frameworks like Ruby on Rails, and practical examples of its implementation in Python with Flask. Carson explains how separating concerns with MVC can reduce code duplication, support both JSON APIs and hypermedia, and maintain flexibility in application 01-frontend."
4 created: 2024-01-16
5 modified: 2024-01-16
6 authors: [ "Carson Gross" ]
7 tags: ["guides"]
8 ---
9
10 A common objection I see to using htmx and hypermedia is something along the lines of:
11
12 > The problem with returning HTML (and not JSON) from your server is that you'd probably also like to serve mobile
13 > apps and don't want to duplicate your API
14
15 I have already outlined in [another essay](/essays/splitting-your-apis) that I think you should split your JSON API &
16 your
17 hypermedia API up into separate components.
18
19 In that essay I explicitly recommend "duplicating" (to an extent) your API, in order to
20 disentangle your "churny" web application API endpoints that return HTML from your
21 stable, regular & expressive JSON Data API.
22
23 In looking back at conversations I've had around this idea with people, I think that I have been assuming familiarity
24 with a pattern that many people are not as familiar with as I am: the
25 [Model/View/Controller](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) (MVC)
26 pattern.
27
28 ## An MVC Intro
29
30 I was a little shocked to discover [in a recent podcast](https://www.youtube.com/watch?v=9H5VK9vJ-aw) that many younger
31 web developers just don't have much experience with MVC. This is perhaps due to the Front-end/Back-end split that
32 occurred when Single Page Applications became the norm.
33
34 MVC is a simple pattern that predates the web and can be with nearly any program that offers a graphical interface
35 to a user.
36
37 The rough idea is as follows:
38
39 * A "Model" layer contains your ["Domain Model"](https://en.wikipedia.org/wiki/Domain_model). This layer contains the
40 domain logic specific to the application. So, for example, a contact management application will have contact-related
41 logic in this layer. It will not have references to visual elements in it, and should be relatively "pure".
42
43 * A "View" layer contains the "view" or visual elements that are presented to the user. This layer often (although not
44 always)
45 works with model values to present visual information to the user.
46
47 * Finally, a "Controller" layer, which coordinates these two layers: for example it might receive an update from a user,
48 update a Model and then pass the updated model to a View to display an update user interface to the user.
49
50 There are a lot of variations, but that's the idea.
51
52 Early on in web development many server side frameworks explicitly adopted the MVC pattern. The implementation
53 that I'm most familiar with is [Ruby On Rails](https://rubyonrails.org/), which has documentation on each of these
54 topics: [Models](https://guides.rubyonrails.org/active_record_basics.html) that are persisted to the database,
55 [Views](https://guides.rubyonrails.org/action_view_overview.html) for generating HTML views, and
56 [Controllers](https://guides.rubyonrails.org/action_controller_overview.html) that coordinate between the two.
57
58 The rough idea, in Rails, is:
59
60 * Models collect your application logic and database accesses
61 * Views take Models and generate HTML via a templating language ([ERB](https://github.com/ruby/erb), this is
62 where [HTML sanitizing](https://en.wikipedia.org/wiki/HTML_sanitization) is done, btw)
63 * Controllers take HTTP Requests and, typically, perform some action with a Model and then pass that Model on to a
64 View (or redirect, etc.)
65
66 Rails has a fairly standard (although somewhat "shallow" and simplified) implementation of the MVC pattern, built on
67 top of the underlying HTML, HTTP Request/Response lifecycle.
68
69 ### Fat Model/Skinny Controller
70
71 One concept that came up a lot in the Rails community was the notion of
72 ["Fat Model, Skinny Controller"](https://riptutorial.com/ruby-on-rails/example/9609/fat-model--skinny-controller). The
73 idea here is that your Controllers should be relatively simple, only maybe invoking
74 a method or two on the Model and then immediately handing the result on to a View.
75
76 The Model, on the other hand, could be much "thicker" with lots of domain specific logic. (There are objections
77 that this leads to [God Objects](https://en.wikipedia.org/wiki/God_object), but let's set that aside for now.)
78
79 Let's keep this idea of fat model/skinny controller in mind as we work through a simple example of the MVC pattern and
80 why it is useful.
81
82 ## An MVC-Style Web Application
83
84 For our example, let's take a look at one of my favorites: an online Contacts application. Here is a Controller method
85 for that application that displays a given page of Contacts by generating an HTML page:
86
87 ```python
88 @app.route("/contacts")
89 def contacts():
90 contacts = Contact.all(page=request.args.get('page', default=0, type=int))
91 return render_template("index.html", contacts=contacts)
92 ```
93
94 Here I'm using [Python](https://www.python.org/) and [Flask](https://flask.palletsprojects.com/en/3.0.x/), since I use
95 those in my [Hypermedia Systems](https://hypermedia.systems/) book.
96
97 Here you can see that the controller is very "thin": it simply looks up contacts via the `Contact` Model object, passing
98 a `page` argument in from the request.
99
100 This is very typical: the Controllers job is to map an HTTP request into some domain logic, pulling HTTP-specific
101 information out and turning it into data that the Model can understand, such as a page number.
102
103 The controller then hands the paged collection of contacts on to the `index.html` template, to render them to
104 an HTML page to send back to the user.
105
106 Now, the `Contact` Model, on the other hand, may be relatively "fat" internally: that `all()` method could have a bunch
107 of domain logic internally that does a database lookup, pages the data somehow, maybe applies some transformations or
108 business rules, etc. And that would be fine, that logic is encapsulated within the Contact model and the Controller
109 doesn't have to deal with it.
110
111 ### Creating A JSON Data API Controller
112
113 So, if we have this relatively well-developed Contact model that encapsulates our domain, you can easily create a
114 _different_ API end point/Controller that does something similar, but returns a JSON document rather than an HTML
115 document:
116
117 ```python
118 @app.route("/api/v1/contacts")
119 def contacts():
120 contacts = Contact.all(page=request.args.get('page', default=0, type=int))
121 return jsonify(contacts=contacts)
122 ```
123
124 ### But You Are Duplicating Code!
125
126 At this point, looking at these two controller functions, you may think "This is stupid, the methods are nearly
127 identical".
128
129 And you're right, currently they are nearly identical.
130
131 But let's consider two potential additions to our system.
132
133 #### Rate Limiting Our JSON API
134
135 First, let's add rate limiting to the JSON API to prevent DDOS or badly written automated clients from swamping our
136 system. We'll add the [Flask-Limiter](https://flask-limiter.readthedocs.io/en/stable/) library:
137
138 ```python
139 @app.route("/api/v1/contacts")
140 @limiter.limit("1 per second")
141 def contacts():
142 contacts = Contact.all(page=request.args.get('page', default=0, type=int))
143 return jsonify(contacts=contacts)
144 ```
145
146 Easy.
147
148 But note: we don't want that limit applying to our web application, we just want it for our JSON Data API. And, because
149 we've split the two up, we can achieve that.
150
151 #### Adding A Graph To Our Web Application
152
153 Let's consider another change: we want to add a graph of the number of contacts added per day to the `index.html`
154 template in our HTML-based web application. It turns out that this graph is expensive to compute.
155
156 We do not want to block the rendering of the `index.html` template on the graph generation, so we will use the
157 [Lazy Loading](/patterns/loading/lazy-load) pattern for it instead. To do this, we need to create a new endpoint, `/graph`,
158 that returns the HTML for that lazily loaded content:
159
160 ```python
161 @app.route("/graph")
162 def graph():
163 graphInfo = Contact.computeGraphInfo(page=request.args.get('page', default=0, type=int))
164 return render_template("graph.html", info=graphInfo)
165 ```
166
167 Note that here, again, our controller is still "thin": it just delegates out to the Model and then hands the results on
168 to a View.
169
170 What's easy to miss is that we've added a new endpoint to our web application HTML API, but _we haven't added it to
171 our JSON Data API_. So we are **not** committing to other non-web clients that this (specialized) endpoint, which
172 is being driven entirely by our UI needs, will be around forever.
173
174 Since we are not committing to *all* clients that this data will be available at `/graph` forever, and since we
175 are using [Hypermedia As The Engine of Application State](/essays/hateoas) in our HTML-based web application, we are
176 free to remove
177 or refactor this URL later on.
178
179 Perhaps some database optimization suddenly make the graph fast to compute and we can include it inline in the
180 response to `/contacts`: we can remove this end point because we have not exposed it to other clients, it's just there
181 to support our web application.
182
183 So, we get the [flexibility we want](/essays/hypermedia-apis-vs-data-apis) for our hypermedia API, and the
184 [features](/essays/hypermedia-apis-vs-data-apis) we want for our JSON Data API.
185
186 The most important thing to notice, in terms of MVC, is that because our domain logic has been collected in a Model,
187 we can vary these two APIs flexibly while still achieving a significant amount of code reuse. Yes, there was a lot
188 of initial similarity to the JSON and HTML controllers, but they diverged over time.
189
190 At the same time, we didn't
191 duplicate our Model logic: both controllers remained relatively "thin" and delegated out to our Model object to do
192 most of the work.
193
194 Our two APIs are decoupled, while our domain logic remains centralized.
195
196 (Note that this also gets
197 at [why I tend not to use content negotiation](/essays/why-tend-not-to-use-content-negotiation) and return HTML & JSON
198 from the same endpoint.)
199
200 ## MVC Frameworks
201
202 Many older web frameworks such
203 as [Spring](https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/mvc.html),
204 [ASP.NET](https://dotnet.microsoft.com/en-us/apps/aspnet/mvc), Rails have very strong MVC concepts that allow you to
205 split
206 your logic out in this manner extremely effectively.
207
208 Django has a variation on the idea called [MVT](https://www.askpython.com/django/django-mvt-architecture).
209
210 This strong support for MVC is one reason why these frameworks pair very well with htmx and those communities are
211 excited
212 about it.
213
214 And, while the examples above are obviously biased
215 towards [Object-Oriented](https://www.azquotes.com/picture-quotes/quote-object-oriented-programming-is-an-exceptionally-bad-idea-which-could-only-have-originated-edsger-dijkstra-7-85-25.jpg)
216 programming, the same ideas can be applied in a functional context as well.
217
218 ## Conclusion
219
220 I hope that, if it is new to you, that gives you to a good feel for the concept of MVC and shows how that, by adopting
221 that
222 organizational principle in your web applications, you can effectively decouple your APIs while at the same time
223 avoiding
224 significant duplication of code.