Blog

Encapsulate What Varies

Nicholas CloudNicholas Cloud is a Software Architect at appendTo and has a real passion for deconstructing business problems, creating abstract, reusable and flexible solutions, and creating awesome software that rocks. Nicholas writes about what drives him when he is architecting software for clients, encapsulating code for ease of maintainability and readability.

I was once asked in an interview: Which object-oriented design principle do you think is most important?. The answer was an easy one. Encapsulate what varies. This principle has become my motto for development, and is the tag-line for my own blog. Whenever I evaluate my own code (or the code of others), I always look for ways to use this principle to make code more expressive and maintainable. I want to write simple, terse, bite-sized code that is easily digested. When I pay attention to what varies in my code–when I start to see where things are common yet divergent–I can refactor to enable future changes while attaining further clarity in the present. The tangible artifacts of this practice tend to be:

  • expressive methods/functions
  • concrete member names
  • more modules/classes
  • shorter modules/classes
  • fewer mortal enemies

When I return to my own code after a period away it is easier to grok and extend. And clients like that.

In this post, I will examine two common scenarios in which encapsulation can be used to deconstruct poor code and create better implementations. These examples, though contrived, are not exaggerated.

Branching statements

Branching statements often indicate variation. You have probably seen (or written) code that looks like this:

//assumes no particular view framework
function UserDetailsView (user) {
  this.user = user;
}

UserDetailsView.prototype.render = function () {
  if (this.user.role === 'teacher') {
    this.showClassRoster();
  } else if (this.user.role === 'student' && !this.user.isGraduated) {
    if (this.user.classmates.length) {
      this.showClassmates();
    }
  } else {
    this.showWelcome();
  }
};

Though this example uses an if/else statement, we can easily imagine a switch/case in its place. There are several things that vary in this method:

  • how the view determines which DOM elements it must render
  • what the view actually does when it renders

Notice that it is the view that varies, not the user, though the user is tested to determine which path execution must travel. It is entirely possible (and likely) that we will see these kinds of branching statements elsewhere in our view:

UserDetailsView.prototype.onContactInfoFormSubmitted = function (e) {
  var validationMethod = this.defaultValidationMethod;
  if (this.user.role === 'teacher') {
    validationMethod = this.teacherValidationMethod;
  }
  if (!validationMethod()) {
    this.showValidationError();
    e.stopPropagation();
    e.preventDefault();
  }
};

As more roles are added, these methods will be expanded to account for diverging scenarios, and the code will become complex and unmaintainable. At any given time, the state of this view should adapt to one–and only one–user role, but bugs will be introduced and the view state will become corrupted. Suddenly behavior intended for students will mysteriously execute for teachers, and we will find ourselves spending hours debugging to figure out why.

The solution is simple: encapsulate what varies. And what varies is the view itself, with respect to user roles. There are three states we need to account for: a default state, a teacher state, and a student state. We can see that behavior diverges when rendering, and during validation.

// DEFAULT VIEW
function UserDetailsView (user) {
  this.user = user;
}
UserDetailsView.prototype.showWelcome = function () {/*...*/};
UserDetailsView.prototype.showValidationError = function () {/*...*/};
UserDetailsView.prototype.render = function () {
  this.showWelcome();
};
UserDetailsView.prototype.onContactInfoFormSubmitted = function (e) {
  if (!this.validate()) {
    this.showValidationError();
    e.stopPropagation();
    e.preventDefault();
  }
};

// STUDENT VIEW
function StudentDetailsView(user) {
  UserDetailsView.call(this, user);
}
StudentDetailsView.prototype = new UserDetailsView();
StudentDetailsView.prototype.render = function () {
  if (this.user.classmates.length) {
    this.showClassmates();
  }
};

// TEACHER VIEW
function TeacherDetailsView(user) {
  UserDetailsView.call(this, user);
}
TeacherDetailsView.prototype = new UserDetailsView();
TeacherDetailsView.prototype.validate = function () {
  //teacher-specific validation
};
TeacherDetailsView.prototype.render = function () {
  this.showClassRoster();
};

Each view now manages its own role-based state, and all methods are more expressive and more terse than our original design. The problem of instantiation still remains. It may be solved any number of ways, but with encapsulation in mind, we will allow each view to determine if it should be rendered or not. We will do this by:

  1. Adding a handles method to the constructor of each view. It returns a boolean value after evaluating its arguments to determine if the view should be instantiated.
  2. Registering all views with a “static” collection on the UserDetailsView constructor via a register method.
  3. Instantiating a view by calling UserDetailsView.create() instead of newing up one directly. This method acts as a simple factory method. Its arguments will be passed to each registered constructor’s handle method, and the first view that can handle them will be instantiated.
function UserDetailsView (user) {/*...*/}
/*
 * Constructors can be registered with the base
 * constructor
 */
UserDetailsView.ctors = [];
UserDetailsView.register = function (ctor) {
  UserDetailsView.ctors.push(ctor);
};
/*
 * The `create` method will be called in lieu
 * of direct view instantiation.
 * Assume underscore.js
 */
UserDetailsView.create = function (/*arguments*/) {
  var args = arguments;

  // find the ctor that can handle arguments
  var ctor = _.first(UserDetailsView.ctors, function (ctor) {
    return ctor.handles.apply(null, args);
  });

  // if no ctor handles arguments, assume UserDetailsView
  ctor = ctor || UserDetailsView;

  // factory function can pass all args to any view ctor by
  // using `Function.apply`; this allows each view to have
  // any constructor parameters that it wishes
  function Factory() {
    return ctor.apply(this, args);
  }
  Factory.prototype = ctor.prototype;
  var instance = new Factory();
  ctor.prototype.constructor.apply(instance, args);
  return instance;
};

/*
 * Set up `handles` method for teacher view
 * and register it with the base constructor
 */
function TeacherDetailsView(user) {/*...*/}
TeacherDetailsView.handles = function (user) {
  return !!user &&
    user.role === 'teacher';
};
UserDetailsView.register(TeacherDetailsView);

/*
 * Set up `handles` method for student view
 * and register it with the base constructor
 */
function StudentDetailsView(user) {/*...*/}
StudentDetailsView.handles = function (user) {
  return !!user &&
    user.role === 'student' &&
    !user.isGraduated;
};
UserDetailsView.register(StudentDetailsView);

/*
 * Get a view instance from the factory method
 */
var user = {
  role: 'teacher',
  name: 'Obi Wan Kenobi'
};

var view = UserDetailsView.create(user);
// (view instanceof UserDetailsView) === true
// (view instanceof TeacherDetailsView) === true

This becomes even more practical when using a loader like require.js. Sub-views can be loaded and registered with the generic, default view. Other modules only need to require the default view to gain access to its factory method and all views it subsumes.

define([
  'underscore',
  'views/StudentDetailView',
  'views/TeacherDetailView'
], function (_) {

  function UserDetailView(user) {/*...*/}
  UserDetailView.register = function (ctor) {/*...*/};

  var ctors = Array.prototype.slice.call(arguments, 1);

  _.each(ctors, function (ctor) {
    UserDetailView.register(ctor);
  });

  return UserDetailView;
});

// elsewhere...

define([
  'views/UserDetailView'
], function (UserDetailView) {
  var user = {
    role: 'student',
    name: 'Anikan "Cranky Pants" Skywalker'
  };

  var view = UserDetailsView.create(user);
  view.render();
});

Each view is now responsible for its own state, and for rendering only the DOM elements with which it should be concerned. Errors are less likely to be introduced because each view does a limited number of well understood operations, and state manipulation is uncomplicated. Code that interacts with these views, via the factory method, will not care that the views are actually different implementations, only that they share a uniform interface and may be used in identical ways.

External state checks

Encapsulation can also be a powerful tool for eliminating external state checks (checking an object’s state from “the outside”). I see this kind of code often:

var library = {
  checkoutBook: function (customer, book) {
    if (customer &&
      customer.fine <= 0.0 &&
      customer.card &&
      customer.card.expiration === null &&
      book &&
      !book.isCheckedOut &&
      (!book.reserveDate || book.reserveDate.getTime() > (new Date()).getTime())) {
      customer.books.push(book);
      book.isCheckedOut = true;
    }
    return customer;
  }
};

This code has several problems:

  1. You have to read, and understand, every condition in this function to know what it actually does.
  2. The criteria for determining if a customer can check out a book, and if a book can itself be checked out, is external to those objects. This means that this code must be duplicated if this check needs to be performed in another location.
  3. New team members, ignorant that it already exists in the code base, might try to re-implement this algorithm elsewhere. They will likely get it wrong because they are unaware of every condition involved (unless this has been studiously documented somewhere, which is a laughable).

The variations in this method are, of course, the conditions that need to be checked. We can eliminate the ambiguity by reducing this method to a few lines and encapsulating the conditions into their respective objects:

var library = {
  checkoutBook: function (customer, book) {
    if (customer.canCheckoutBook() && book.isAvailable()) {
      customer.checkout(book);
    }
    return customer;
  }
};

var customer = {
  canCheckoutBook: function () {
    return !this.hasFine() &&
      this.hasActiveLibraryCard();
  },
  hasFine: function () {
    return this.fine > 0.0;
  },
  hasActiveLibraryCard: function () {
    return this.card !== null &&
      this.card.expiration === null;
  },
  checkout: function (book) {
    //implementation
  }
};

var book = {
  isAvailable: function () {
    return !this.isCheckedOut &&
      !this.isReserved();
  },
  isReserved: function () {
    return this.reserveDate !== null &&
      !this.isFutureReserve();
  },
  isFutureReserve: function () {
    return this.reserveDate.getTime() > 
      (new Date()).getTime();
  }
};

And, of course, when checkout conditions change–as we know they will–we can update our code in customer and book without touching library, or any other module or object that depends on these entities. Since no other code makes external state checks, our objects are well encapsulated.

Conclusion

In the real world, every person has different tastes, preferences, goals and values. People who live in close communities tend to share a homogeneous culture, and so their values align more often than not. As society grows and new members are introduced, the likelihood of cultural divergence grows. Values begin to differ. People make different choices about how to use their time, energy, resources, labor.

Direct exchange of goods and services becomes difficult because of specialization, and so a common exchange medium is needed for society to scale. This medium–this tool of encapsulation–is currency. When I hand a few dollars to a barista for my coffee, I avoid the necessity of exchanging my particular skills or or time for hers. Indeed, I would most likely be long in the throes of caffeine withdrawal before we could agree on an exchange rate for “hours of programming” to “cups of coffee”. Instead we use currency to encapsulate our labor (I want to spend my time programming; the barista, crafting fine coffee). That the person in line behind me writes books, and the person behind her fixes automobiles, and the person behind him runs a non-profit is irrelevant; they will all use the same currency to buy coffee. The currency encapsulates what varies.

Our code is not unlike the real world. As complexity increases, as our code base grows, things will vary greatly as new business cases are introduced and old ones are refined. The reason we encapsulate code is so that we can isolate those differences behind common, unambiguous protocols, though the implementation of each variation may in fact be complicated.

Now go forth and encapsulate what varies.

Tweet about this on TwitterShare on FacebookShare on RedditShare on Google+Share on LinkedIn