The Monolith Component

It is more common than ever to have user interfaces made up of components. With so many user interface libraries and frameworks like Angular, React, VueJS, Aurelia and KnockoutJS components are everywhere. Components are the building blocks of a user interface. It is imperative that these blocks are built and organized in a way that supports proper testing, reduces defects and enables the extension requirement innate to an ever-changing user experience. This article will describe a component that counters these goals by challenging both the quality and flexibility of a user interface: The Monolith Component.

The Monolith Component is a byproduct of feature-driven functional decomposition. It is the user interface representation of the god object. The component is feature-packed, contains excessive amount of code, and often becomes the grandparent of smaller child components. To make the problem worse, the child components could be referencing the grandparent and act as nothing more than a visual proxy to grandparent capabilities.

It isn’t hard to understand why this sort of thing happens. First, an agile team will use sprints to deliver features. Without enough careful consideration and planning of system design, the design and functionality tends to focus on feature-level concerns at a sprint cadence. Second, its not always intuitive to design something that is counter to our nature. For example, generally speaking we first learn how to cook from our parents, and our parents first learned how to cook from their parents, and so on. In a fast-paced environment, a quicker path may be just to learn from your grandparents. This is a small example of the innate grandparent (monolith) design we exist within. Instead of children components owning their responsibilities, they are implemented in their parents and likewise up the hierarchy to the level of the monolith component.

Applying the grandparent theme to user interface development leads to components that are too hard to maintain, test, extend and keep out bugs. Overall, a monolith component will have too many responsibilities.

Identifying A Monolith Component

There are a few indicators of a monolith component.

#1 Line Count: if you see a component with 1000+ lines of code, you may be looking at a monolith component.

#2 Dependencies: if you see dozens of dependencies or more, you may be looking at a monolith component.

#3 Bugs: if most bug fixes involve looking at the same, single component, you may be looking at a monolith component.

#4 New Features: if new features involve looking at the same, single component, you may be looking at a monolith component.

#5 Responsibility: if it is easier to describe what a component does not do within the context of the page, you may be looking at a monolith component.

Refactoring A Monolith Component

Updating a monolith component can be a daunting task. It should get easier the more it is done. It does get easier if those updates mean breaking up the monolith into a more sane design. The more that is done, the better off the code (and the developer) will be. To describe exactly how to refactor one of these component would depend on its implementation details. I will instead attempt to describe some general ideas that have helped me in the past with some simple examples along the way.

Test Test Test

The first step is having confidence that refactoring does not introduce breaking changes. To this end, maintaining tests that prove business value is essential. The presentation and logic shouldn’t change during a refactor. That is to say, the intent should not change. There are multiple ways to accomplish the same thing. Refactoring code is meant to update code so that it does the same thing in a cleaner way. Having tests that make sure the code satisfies business requirements without depending on how it satisfies them, will help avoid introducing bugs while refactoring.

Identify Responsibilities

The second step is knowing what the component does. A monolith component will likely have multiple responsibilities. Being able to list these will help us understand the component and how it can be split up. It can reveal the patterns and domains that shape the component.

Responsibilities that are determined to be unnecessary should be removed:

Example 1: Code is disabled due to being wrapped in a comment. This code can’t execute. Remove it. Be careful when looking at comments in HTML. There are various libraries and frameworks that give meaning or functionality to HTML comments.

Example 2: A block of HTML never displays because of a visibility condition that is never and can never be true. Assuming this isn’t a bug, the HTML block can be removed. The condition in code may not be necessary either.

We know the component’s responsibilities and we may have removed some that were not needed. Now we look at dependencies.

Understand Dependencies

The third step is knowing the internal and external dependencies of the component. The goal of this step is to answer: what does the component require so that it can perform its responsibilities?

Depending on what kind of dependency injection is used (the application does leverage DI right?) dependencies may be specified in different locations.

Looking at the constructor is a good place to start. The parameters of the constructor define what a component needs in order for an instance to be created.

Next, look at the private and public properties. These will likely include the values or objects set in the constructor. They also represent the possible states of a component. Maybe an enum is used to define how to present a particular object in the view. Maybe a boolean is set to determine whether a checkbox should be checked on load. Maybe an object is used to store a server response object. These things can still be considered dependencies in this context – the component needs them to provide its business value.

Look for static members. Static members need a definition not an instance. What do they offer and how does the component use them? Generally, these can be easy to identify and extract to be more re-usable.

Finally look at how the dependencies are used within instance methods. If a non-primitive data type is specified in the constructor, what is the purpose of that dependency? Does it allow a consumer to get data from a server? Does it contain methods to filter a list of a particular data type? Is it the mechanism for triggering an event on a timer? Knowing how the dependencies are used can help when determining what business problem they are solving. This in turn, can help group dependencies by domain.

Extract Common Ground

The fourth step is knowing the groups of common responsibilities and common dependencies that can be moved into other distinct components.

Find themes such as api calls, orchestration of child components, notification, and other domain logic.

Use a separate class to encapsulate api calls. This enables centralized control over forming requests and normalizing responses.

Use a dedicated component for handling the interaction between child components. Using a dedicated class to share data can help avoid coupling as well.

Use a separate class or component to handle other domain logic:

Example 1: The presentation of a timer is maintained. The timer is triggered, tracked, displayed, stopped and reset within the monolith component.

Example 2: The component allows the user to update the view with new data from the server without using the browser refresh button. After a user triggers a refresh: a server request is formed, the request is sent, a response is received and parsed, it is then sent to areas that need the parsed response and the view is updated appropriately.

Example 3: User input is maintained. A form contains multiple labels and input controls. The user input is validated. When the user input is invalid, a notification is displayed to the user. When a user completes the form, it can be submitted to the server so there are more server requests and responses to handle.

All of the logic and presentation of these examples can be contained in separate classes and components. They will take with them the necessary responsibilities and dependencies of the monolith component – only what they need.

Repeat As Necessary

The fifth step is knowing what is left after extracting the common ground. If we are lucky, this means the monolith component now does only one thing. If not, repeat the previous steps until the component does just one thing. This is assuming that all of the responsibilities of the component will be known and are necessary.

A monolith component is too big. It does too much. It knows too much. It has too many responsibilities. As developers, we are responsible for delegation. If a component does too much, it is our fault. There are many ways to prevent and refactor monolith components. There have been volumes of work describing refactoring methodologies. This article describes some ways that have worked for me when refactoring a monolith component.


Working with Vanilla JS in Web Applications

Why use Vanilla JS instead of any number of the frameworks available or even TypeScript? The answer is largely irrelevant if a choice has already been made. However, deciding to replace JavaScript with some alternative for all use cases is an absolutism missing the mark. This article will describe the use of Vanilla JS leaving the choice of what language to use up to you.

Class Definitions & Namespaces

ES6 classes are not yet fully supported in the browser. Many of the limitations mentioned in this article are most relevant when developing with ES5 – such as developing for Internet Explorer or other antiquated browsers. Even without full support of classes, a similar effect can be achieved in JavaScript and it is actually quite easy to do!

We first want to make sure that the class definition is contained. This means it should not pollute the global namespace with methods and variables. This can be accomplished by using a closure – a specific one called an IIFE.

(function (global) {
  "use strict";

  global.API = new MyObject();

  function MyObject() {
    var self = this;

    ... var privateVariable ...

    ... function privateMethod() ...

    ... self.publicMethod ...

Notice that the global namespace is passed to the IIFE – since they are just methods, they can be used as such! If you want to know more about how the global namespace is obtained, check out this enlightening StackOverflow post: (1,eval)(‘this’) vs eval(‘this’) in JavaScript?

“Use Strict”

"use strict"; //seriously, do it.

The class can be initialized and stored at global scope such as inside a single app-specific namespace:

(function (global,app,http) {
  "use strict";
  global[app] = global[app] || {};
  global[app][http] = new Http();
  // global.App.http.publicMethods()

  function Http() {
     var self = this;
     // var privateVariables ...

     // self.publicMethods = function ...

     // function privateFunctions() ...

I find it easier to write client-side JavaScript as an API. Leveraging the design patterns this encourages offers many benefits to code quality and maintenance. In the code above, an instance of Http is assigned to the http property in the global.App namespace. Certainly, this should contain our methods for making HTTP calls! Code organization is one of the best things about approaching the application’s client-side JavaScript in this way. Usually, the constructor function, not an instance, would be stored – which allows certain SOLID principles to be applied.

The Constructor Function

The Http function is a special kind – a constructor function. This means an instance can be created using the new operator with the constructor function call.

function MyObject() {

var instance = new MyObject();

This should look familiar if you have ever created an instance in Object-Oriented code before.

Capturing this

The fact this isn’t always the same is both the power and the curse of JavaScript. The first line of the Http constructor function is capturing this in a specific context to help overcome the curse, and leverage the power:

function Http() {
  var self = this;


At the scope of the constructor function, this refers to the Http object. A private variable is declared and initialized to capture it and make it available to all public and private members of Http – no matter what this happens to be during the invocation of those members. Capturing this only once and at the scope of the corresponding constructor function will reduce the possibility of this fulfilling its curse!

private Members

The variables and functions created at the scope of the Http constructor function will be available to all public and private members within the Http object.

function Http() {
  var self = this,
      eventHandlers = {};

  function addEventHandler(event, handler) { }
  function removeEventHandler(event, handler) { }

In this case, self, eventHandlers, and the add/remove event handler functions are private members of Http. They are not accessible to external sources – only public and private members of Http can access Http‘s private members.

public Members

The properties and methods exposed on the Http object, such as those existing in the prototype chain, that can be accessed from external sources, are considered public.

function Http() {
  var self = this;

  self.get = function (request) { ... = function (request, data) { ...

Add public members to the self variable within the constructor function. This allows other code to perform the operations of an Http instance.

static Members

Members can be static as well. By declaring a variable on the constructor function itself, it can be assigned a value, instance, or function that is public while not depending on an instance to be created using the constructor function:

function Http() {

Http.setup = function () { ...

The static Http member can be used without creating an Http instance:

// ... application code doesn't create an Http instance
// ... application code doesn't create an Http instance

The member is public and available anywhere the Http constructor function is available.

Execution Contexts

Without going into the depths of execution contexts in JavaScript, there are a few things to note. This section will describe a couple different execution contexts and integration points at which JavaScript code is executed.

Global Context

There is only 1 global context – or global scope or global namespace. Any variable defined outside a function exists within the global context:

var x = 9;
function XManager() {
  var self = this;
  self.getX = function () { return x; }
  self.setX = function (value) { x = value; }

The global-scoped x variable is defined outside of the XManager function and assigned the value of 9. When getX is called, it will return the global-scoped x (the value of 9).

Local Scope – Function Execution Context

The alternative to the Global Scope is Local Scope. The local scope is defined by the function execution context:

var x = 9;
function XManager() {
  var self = this,
      x = 10;
  self.getInstanceX = function () {
    return x; // returns 10

In this case, a variable x is declared twice. The first time is within the global execution context. This variable is accessible within XManager. Within the XManager constructor function, the private variable x is declared and initialized to 10. The getInstanceX method will return the variable x that is first in its execution context stack:

Execution Context Stack (David Shariff)

The getInstanceX method is “Active Now”, XManager‘s private variable x is next, followed by the global-scoped variable x, and finally the global execution context. All of this is to explain why getInstanceX returns 10 and not 9. Powerful stuff!

let & Block-Level Scope

I cannot discuss execution contexts without mentioning the keyword let. This keyword allows the declaration of block-level scope variables. Like ES6 classes, if antiquated browsers need to be supported, the let keyword will not be available.

function Start() {
  let x = 9;          // variable assigned to value 9
  function XManager() {
    let x = 10;       // different variable assigned to value 10
    function getX() {
      console.log(x); // return 10
    console.log(x);   // return 10
  console.log(x);     // return 9

A block scope variable is accessible within its context (Start) and contained sub-blocks (XManager). The main difference from var is that the scope of var is the entire enclosing function. This means, when using let, XManager and the contained sub-blocks (getX) have access to the new variable x assigned to the value of 10 while the variable x in the context of Start will still have the value of 9.

Event Handlers

Client-side JavaScript code is triggered by the user through DOM events as they interact with rendered HTML. When an event is triggered, its subscribers (read event handlers) will be called to handle the event.

HTML – Event Subscription

<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
<div id="submit">Button</div>

JAVASCRIPT – Event Subscription

var button = document.getElementById("submit");
button.addEventHandler('click', clickHandler);

JAVASCRIPT – Event Handler

function clickHandler() {
  console.log("Click event handled!");

Event handling marks the integration point between user interaction with HTML and the application API in JavaScript.

Understanding how to create objects and the Execution Context is important when writing client-side JavaScript. Designing the JavaScript as an API will help to further manage the pros and cons of the language.