W

State Is Not Data

September 25, 2019

Differentiating between data and state leads to cleaner code. What’s the difference? When you instantiate and object with data you create an object with state.

class User {
  constructor(dataJson) {
    this.fname = dataJson.fname;
    this.lname = dataJson.lname;
  }
}

newUser = new User({fname: "Jack", lname: "Frost"})

The object newUser is an object with the state fname = Jack and lname = Frost. Data, in this example, is the json object.

Let’s say we need to generate the User’s full name. Object oriented programming would have us add a method to User to concantenate fname and lname. You can skip instantiating the object and just operate on the data like so:

jsonUser = {fname: "Jack", lname: "Frost"}

function fullName(data) {
  return data.fname + " " + data.lname;
}

fullName(jsonUser) === "Jack Frost"

Don’t instantiate state just to operate on data.

Send comments, corrections to waynechoi@gmail.com