5 Tips For Writing More Maintainable JavaScript Code

There are at least a few development rules we are always aware of at Functionite while working on the JavaScript applications. We have picked 5 of them to show what we have learned over last few years that makes our code way more maintainable.

Always stay conservative

We believe that removing code is better than adding it. Being adventurous in writing new functionality is often looking for troubles by introducing another level of complexity. Instead, we should measure our code quality by how many lines we removed or how little code we’ve added. Never the other way around.

We strongly recommend reading this nice write-up on Programming Is Terrible blog — on how to create code that is easy to delete.

Avoid fat views

Another thing everyone should avoid is implementing a business logic in the views. It always puts our application off the track so it becomes unmaintainable in the long run. In MVC design pattern it’s a model who keeps the business logic and never a view. Let’s take a look at the following example in which a view removes a single model, which in turn is linked with the other items that also should be removed:

View.prototype.onClick = function () {
    var otherThings;
    if (this.model.canRemove()) {
        this.model.remove();
        otherThings = this.model.getOtherThings();
        otherThings.forEach(function (thing) {
          thing.remove();
        });
    }
};

View that contains such part is often called a fat view. It means it is implementing a lot of unnecessary business logic whereas it should have a single responsibility. In the above snippet, the view is responsible not only for calling remove function on the model, but also for removing otherThings from that model. It makes the code harder to test and maintain.

In order to write some unit tests, we’d need to test both the view and the model, instead of just the model. This is a sign that something is wrong. Code that removes otherThings should be put into remove method in a model.

Model.prototype.remove = function () {
  this._removeMyself();
  this.getOtherThings().forEach(function (thing) {
    thing.remove();
  });
};

View.prototype.onClick = function () {
    if (this.model.canRemove()) {
        this.model.remove();
    }
};

As you can see, it’s worth including information about which function (and/or module) failed and what a given input was. It makes debugging faster and environment-independent.

Read more @ Medium