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

Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.

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!

Monitor application stability with Bugsnag to decide if your engineering team should be building new features on your roadmap or fixing bugs to stabilize your application.Try it free.

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 }}