Case Statement

  • Archive
  • RSS

Instance Variable Shelf

Too often I see code that does the following:

declare('Foo', {
  constructor: function(input) {
     this._input = input;
     return new Bar(this._input)
  }
});

Chances are that Bar also copies input into an instance variable. Soon there’s a chain of three or four classes all maintaining input’s state. If Bar later updates input with a new struct, all of the other copies are stale and invalid. The only solution at that point is to bubble a change event throughout the tree so that each instance gets updated.

But it’s totally unnecessary. Foo likely doesn’t need to keep a reference to input. If it does need it for some operation later on, Foo should ask Bar (and Bar should ask whomever is holding the canonical copy).

This is why the functional programming people say that mutable state is the source of most bugs. This may seem obvious now, but it’s incredibly easy to make this mistake if you aren’t paying attention. Think really hard before creating a new instance variable. Think extra hard about creating a second reference to that variable anywhere else in your code. Instance variables are longer lived than you expect, don’t use them as a shelf.

  • 5 months ago
  • 1
  • Permalink
  • Share
    Tweet

1 Notes/ Hide

  1. qgifs liked this
  2. hiqus liked this
  3. casestatement posted this
← Previous • Next →

About

I'm Case Nelson.
Customer Advocate, Leader, Evangelist, and Hacker.

Portrait/Logo

Follow Me,
I do cool things

  • @casestatement on Twitter
  • snoe on github
  • RSS
  • Random
  • Archive
  • Mobile

Effector Theme by Carlo Franco.

Powered by Tumblr