HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

What is the best way to refactor out “temporal dependence” of instance methods?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
temporalthewhatwaymethodsinstancedependencerefactoroutbest

Problem

For example, suppose in a view class we need to instantiate some UI components and then populate the fields. Something like:

var View = function() {
  this._initUI();
  this._populateFields();
};

View.prototype = {
  _initUI: function() {
    this.textField = new TextField();
    this.comboBox = new Combobox();
  },

  _populateFields: function() {
    this.textField.setText('foo');
    this.comboBox.setVal('bar');
  }
};


This doesn't quite smell right, as you must call _initUI before _populateFields, and it's pretty hidden that _initUI will be creating some instance variables that will later be used by _populateFields.

What's your opinion of a better way of doing this?

Solution

You could have a flag that is set when _initUI is called. The first line of _initUI would check the flag and exit if it's already set; the second line would set it. Then any method which needs _initUI to have been called can simply, safely, call it without fear of double-initializing things.

Context

StackExchange Code Review Q#41705, answer score: 3

Revisions (0)

No revisions yet.