DEV Community

DaniAcu
DaniAcu

Posted on

Modify global variables in 2020 🤔

Hi all, I would like to start writing a post about recommendations or thoughts to share with the community and receive feedback. So here we go.


On the last days I was reading code on different projects and I noticed some code continues using and modifying some global variables in special cases. All these cases are similar and I think that there ways to prevent that. I will just talk about a common case that I noticed and how we could fix it.

In some cases, we want to preserve the id to use it on our apps. All those cases are using an eternal accumulator as id to be sure that all time is a new value.
And we are using something like this:

let _uiid = 1;

/* ... */

function createUser () {
  /* some logic */
  const userID = _uiid++;
}
Enter fullscreen mode Exit fullscreen mode

This code is generating a new id to create a new user with a different id. It's a simple solution, right? But it's changing a global variable and it's opening the door to unexpected changes on the variables because this could change on any part of the code or the system flow.

My proposal here is: use a functional abstraction to prevent that.

function createCounter (defaultState = 0) {
   let state = defaultState ;
   return () => state++;
}

const getID = createCounter(1);
/* ... */

function createUser () {
  /* some logic */
  const userID = getID();
}
Enter fullscreen mode Exit fullscreen mode

Here we are using a global variable but we are not modifying it. So the code is cleaner and readable. You can create and move the createCounter to another file, to reuse it.

It's longer than just use a variable and modify it. But it's helping you to prevent unexpected bugs in the future.

And that's all folks. Let me know what do you think about it in the comments?

Oldest comments (2)

Collapse
 
pentacular profile image
pentacular • Edited

You are modifying it when you call getID.

The difference is that you're using a mechanism which enforces a policy of access to that piece of global state.

Which should tell us that this problem isn't about global variables -- it's about policy enforcement.

If you have es6 modules available, I'd recommend using those to provide this kind of policy mechanism.

// userCounter.js

let id = 0;

export const getNextUserId = () => id++;
Enter fullscreen mode Exit fullscreen mode

// foo.js

import { getNextUserId } from './userCounter.js';
Enter fullscreen mode Exit fullscreen mode

// bar.js

import { getNextUserId } from './userCounter.js';
Enter fullscreen mode Exit fullscreen mode

Which also solves the problem of ensuring that the same counter is used properly in each context that requires that counter.

Collapse
 
daniacu profile image
DaniAcu

Yeah you right, I just use a funny title. Yeah any encapsulation that protects the access to the variable is valid. Thanks for sharing 😊