Models, Views, Controllers

Alice in Userland

Story

The web page works, and Alice cannot stand looking at the file that makes it. HTML is glued together in the middle of code that also reads forms, also decides what to save, also builds links. Everything is in everything. So she goes looking at other people’s projects, the way you do when you know something is wrong but not what. She keeps seeing the same folder names: models, views, controllers, routes. A blog post gives the shape a name. It is called MVC, and it is older than she is.

She tries it on. todo.ts becomes the model and moves into models, untouched, because it was already the only part that knew nothing about anyone. The HTML moves out of the code entirely into views, as a Handlebars template, so the page is a page again and not a string. What is left in the middle goes into controllers: cli.ts for the terminal and http.ts for the browser. Each one takes what the user asked for, tells the model to do it, and hands the answer to a view. main.ts keeps only the routing, both kinds, the commands and the addresses side by side.

Nothing about the app changed. The same commands print the same lines, the page looks the same to Bob. But now she can say where a thing belongs before she writes it, and that is new. She writes down the rule she was missing.

Alice's Notebook

  • Give every command its own function instead of writing its body inside the switch block.
  • Keep the code that reads the terminal apart from the code that knows what a todo is.
  • Handle different concerns in different parts of the program (Single Responsibility Principle).
  • Use a library for the work that is not your program’s real job.
  • Keep the rules in one place, so that you can put a new face on them without changing them.
  • Separate the user interaction mechanism completely from the core logic.

Choose a file from the tree.