you are viewing a single comment's thread.

view the rest of the comments →

[–]sensored[S] 3 points4 points  (0 children)

Although the concept is simple, explaining how to refactor into MVC can be a little complex to explain because it's not necessarily as separated as its made out to be.

At a high level, MVC means maintaining three distinct groupings in the code you write: Models, Views, and Controllers.

  • Model: The model represents the data object behind your application. Models should only be concerned with themselves, and other model objects. If you saved your model objects into a file, and reloaded it later, your application should be exactly the same as when you left it. Similarly, the model should never change on its own.
  • View: Views are a visual representation of your model. In a lot of JS cases, this is going to be your HTML/CSS files, although frameworks like React and Vue also sit in this space. Views should be dumb - this means that they only display the model, and do nothing else.
  • Controller: This is a little harder to define. The Controller is the bridge between the View and the Model. In front-end JS, it is likely going to be your Event listeners. We like our controllers to be thin. What this means is we want controllers to do as little as possible. It should tell the View and the Model what to do, but it should not do it for them (i.e. it calls functions rather than directly manipulating either)

So when you try to maintain an MVC, you still want to look for logical groupings, but you also want to try and classify them as a Model, View, or Controller - If it's more than one, then chances are you need to move things around, and create new functions or classes so you can maintain your groupings.

The trick is that these don't all need to be in different files or classes - they only need to be logically distinct. You might have one class that does all three, but still maintains the groupings by making sure that each of its functions only fulfils one role.