JavaScript Clean Code — Objects and Classes

John Au-Yeung
Level Up Coding
Published in
4 min readMar 10, 2020

--

Photo by The Creative Exchange on Unsplash

When writing clean code we have to be careful about the objects and classes or constructors that we define. We don’t want to expose data that we don’t want the outside world to view, and we want our data structures to be defined in a way that’s easy to reuse.

In this article, we’ll look at how to organize our data in a way that’s easy for us to use.

Use Classes Over Constructor Functions

We should use classes instead of constructor functions. It’s much clearer and inheritance can be done much more easily.

They’re the same underneath. Class syntax is syntactic sugar for the constructor function syntax.

For example, we can define a Person class as follows:

class Person{
constructor(name, age) {
this.name = name;
this.age = age;
}
}

We can see that our constructor takes in name and age as parameters and set it as values of instance variables.

Where it shines is when we need to extend the class. We can create an Employee class that has the instance variables of the Person class and extends it as follows:

class Employee extends Person {
constructor(name, age, employeeCode) {
super(name, age);
this.employeeCode = employeeCode;
}
}

All we have to do is to call the superclass’ constructor with the super call, and then we can set the instance variables of the Employee class in the constructor.

Using Getters and Setters

Getters and setters are good for hiding the actual data that’s being accessed. We can have computed properties, which means that we can abstract way the implementation of those computed properties so that we don’t have to worry about changing the code that uses them when we change the implementation.

Also, setters let us validate before setting the data rather than setting them directly.

Likewise, error handling and logging can also be added easily into them.

We can also lazy load object properties with getters.

For example, we can use getters as follows:

--

--