Encapsulate What Varies

Nicholas 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:

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:

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.

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.

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.

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:

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:

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.


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.

appendTo offers JavaScript Training for Teams.

Kyle Pennell
Kyle Pennell is a marketer and writer with a variety of technical chops (JavaScript, Google Sheets/Excel, WordPress, SEO). He loves clear and helpful copy and likes automating things and making web apps (mostly maps). Found at kyleapennall.com and many other digital spaces