I suggest to take into consideration these ideas for building reliable objects in JavaScript:

  • Split objects in two: data objects and behavior objects
  • Make the data objects immutable
  • Expose behavior and hide data in behavior objects
  • Build testable behavior objects

Data vs Behavior Objects

Essentially there are two kinds of objects in an application:

  • Data Objects — expose data
  • Behavior Objects — expose behavior and hide data

Data Objects

Data objects expose data. They are used to structure and transfer data inside the application.

Let’s take the case of a to-do list application.

This is how the to-do data object, gotten from the server, may look:

{id: 1, title: "This is a title", userId: 10, completed: false }

And this is how a data object used to display information in the view may look:

{id: 1, title: "This is a title", userName: "Cristi", completed: false }

As you can see, both objects contain only data. There is a small difference between them: the data object for the view has userName instead of the userId.

Data objects are plain objects, usually built with object literals.

Behavior Objects

Behavior objects expose methods and hide data.

Behavior objects act on data objects. They may take data objects as inputs or return data objects.

I’ll take the case of the TodoStore object. The responsibility of the object is to store and manage the list of to-dos. It makes the synchronization with the server using the dataService object.

Discover Functional JavaScript was named one of the best new Functional Programming ebooks by BookAuthority!

For more on applying functional techniques to React take a look at Functional React.

Learn how to apply the Principles of Design Patterns.

You can find me on Medium and Twitter.