Model all state in an application

Create a structured representation of the system's state, usually as encapsulated objects, which humans can conceptually understand.

In a Model-View-Controller (MVC) application, the model is responsible for the application's state and non-UI-specific behavior.

A model (the M in MVC) holds the state, logic, and rules of an application, it exists independently of the UI. You could replace React with Vue, replace the DOM with an iPhone UI, and the application's logic would be untouched.

Everything should be modeled. There should be no state that exists within an application that goes un-modeled. Because when data is modeled, it creates structure in application. You can inspect, query, and interrogate it. When you view the model, you should be able to determine the structure and state of your application.

Modeling requires thought to design and a basic understanding of the domain of the application.

Depending on the framework used, the model may look very different from what is above, but the concept will always exist. An example of this is Redux, the React framework. There is no model in the classic sense, but it exists with the combination of the reducer, store, and state.

Example

// A basic User model in vanilla JS
class User {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  setFirstName (firstName) {
      this.firstName = firstName;
  }
  setLastName (lastName) {
      this.lastName = lastName;
  }
}

Or with a more functional approach:

function setFirstName(userObject, firstName) {
    userObject.firstName = firstName;
    return userObject;
}

Some examples of the model concept in other languages and frameworks:

Exceptions

  • Avoiding time-based states, such as animations, can be a good idea. As this can add a lot of complexity.

Further reading: