clean-code-javascript icon indicating copy to clipboard operation
clean-code-javascript copied to clipboard

"Don't write to global functions" section improvement

Open feimosi opened this issue 8 years ago • 3 comments

Two things from my side:

  1. Is there a reason to use Set inside the example function? Considering there's also Array.prototype.includes:
Array.prototype.diff = function diff(comparisonArray) {
-  const hash = new Set(comparisonArray);
-  return this.filter(elem => !hash.has(elem));
+  return this.filter(elem => !comparisonArray.includes(elem));
};
  1. Wouldn't it be better to teach using simple functions instead of whole classes? Who would ever inherit from built-in types and write const arr = new SuperArray(1, 2, 3) in real life? I think it's more common to have:
function diff(first, second) {
  return first.filter(elem => !second.includes(elem));
}

What do you think?

feimosi avatar Mar 23 '17 15:03 feimosi

We could change this whole subsection and use a better example. Thanks for bringing this up! If you have an idea that doesn't involve Array and Set diffing and is something else altogether I'm down to accept a PR!

ryanmcdermott avatar Mar 29 '17 15:03 ryanmcdermott

Sorry, I don't really know a better example at the moment. Usually when you mention not to pollute / mutate global scope, you introduce the idea of modules.

feimosi avatar Apr 01 '17 18:04 feimosi

Maybe something simple like:

Bad:

Array.prototype.last = function() {
    return this[this.length-1];
}

[1,2,3].last();

Good:

function getLastElement(array){
    return array[array.length-1]
}

getLastElement([1,2,3]);

And, yeah, the idea of modules could be better for this kind of example, instead of using new, you could explain little of Module Pattern.

const arrayUtils = {
  last: (array) => array[array.length-1]
}

AlgusDark avatar May 11 '17 14:05 AlgusDark