Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is using side effects bad practice in JavaScript constructors?

I use something quite similar to the design pattern custom objects in my code normally.

But JSLint frowns upon constructs like this:

function MyClass() { this.init(); }
new MyClass(data);

Because the object is being discarded immediately after creation - it isn't being used for anything. We can fool JSLint to ignore this by assigning it to a variable, but it doesn't change that JSLint (and I am guessing many JavaScript enthusiasts) discourages the pattern.

So why is using side effects in a JavaScript constructor seen as a bad practice?

For what it's worth, I thought this was a good practice because:

  1. You have one setup function, thus it should be easier to maintain if e.g. you are managing a list of MyClass instances for access later. (Pushing an object onto an array is a side effect, you would have to do it after the constructor returned to be "good practice" = harder to maintain.)
  2. It has its own prototype, thus a "class ownership": Firebug reports this as an instance of MyClass instead of just Object. (This, in my opinion, makes it superior to the other design patterns.)
like image 742
user1994380 Avatar asked Feb 04 '13 20:02

user1994380


1 Answers

In his book Clean Code, Robert Martin says

Side effects are lies. Your function promises to do one thing, but it also does other hidden things...they are devious and damaging mistruths that often result in strange temporal couplings and order dependencies.

What you described in your comment regarding arrays sounds like a "strange temporal coupling".

like image 60
Aaron Kurtzhals Avatar answered Sep 17 '22 08:09

Aaron Kurtzhals