Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

The Place Where I Will Use Getters in JavaScript

DZone's Guide to

The Place Where I Will Use Getters in JavaScript

A lot of people believe that using getters in your Javascript is a bad idea. Are there any exceptions to this rule? In this post we take a look at one possible exception.

· Web Dev Zone ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

It’s going to be a short one, but powerful.

Do you remember I wrote previously why getters/setters is a bad idea in JavaScript? I didn’t change my mind, I do still think so, but now I found one valid place where I can and DO want use them. You will never guess. (Just kidding.)

Unit tests. Nowadays, I write unit tests and use getters for testing my code. At appears we have a lot of these else, if statements where boolean values are checked, something like this:

function doSomething(options) {
  if (!options.hasZork) {
    return;
  } else if (options.hasBork) {
    return;
  }
}

And this is exactly the place where I can now use getters to test whether hasZork has been checked or not. It helps me to protect my API and ensure that all these evil logical branches are tested:

const sinon = require('sinon');

const hasZork = sinon.spy(() => false);
const hasBork = sinon.spy(() => true);

const options = {
  get hasZork() { return hasZork(); }
  get hasBork() { return hasBork(); }
};

doSomething(options);

// assert that both hasZork and hasBork has been called;

I promised you it would be a short one. The end!

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:
javascript ,getters ,unit tests ,web dev

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}