Over a million developers have joined DZone.

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

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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!

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
javascript ,getters ,unit tests ,web dev

Published at DZone with permission of Maks Nemisj. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}