7 Patterns to Refactor JavaScript Applications: Decorators

Note: This is part seven (prev) of a seven part series that starts here.

When a process has side effects that need to be executed only in certain situations, this functionality can be layered onto an existing operation using Decorators. A Decorator takes an object and wraps auxiliary functionality around it, letting you add on what you need when you need it and keeping the core procedure untouched.

Example

Let’s imagine a Service Object that generates report cards for each student in a class. A teacher can generate these report cards at any point, but there are some situations where those report cards should be mailed to the student’s parent.

One way to address this would be to have two separate Service Objects, GenerateReportCards and GenerateReportCardsAndEmailParent, but this creates duplication and is hard to maintain when there are many cases with many conditional steps.

Another way would be to chain separate services, such as:

new GenerateReportCard(student).run()
  .then(function(student) {
    return new EmailReportCardToParent(student).run()
  })

This isn’t bad, but it relies on the return value from the Service Object to be usable for the subsequent process. Additionally, the same process may need to happen in both procedures, such as generating the HTML for the report card.

This problem calls for a Decorator, which targets a specific method of the object being decorated and wraps it with additional procedures, allowing us to tap into an existing operation and add functionality. So, for this example, our Service Object that will be decorated looks like this:

var _ = require('underscore')

var GenerateReportCard = function(student) {
  this.student = student
};

GenerateReportCard.prototype = _.extend(GenerateReportCard.prototype, {
  
  run: function() {
    return _.compose(
      this.saveReportCardAsPDF,
      this.generateReportCardHtml,
      this.getStudentGrade
    ).call(this)
  },

  getStudentGrade: function() {
    // some actions here to 
    // determine grade
    return grade
  },

  generateReportCardHtml: function(grade) {
    // some actions here to 
    // build html for report card
    return html
  },

  saveReportCardAsPDF: function(html) {
    // some actions here to 
    // save PDF and get the url
    return pdfUrl
  }

});

We could create a Decorator object that accepts an instance of the Service Object as its argument and returns that Service Object with the specified method wrapped with the added functionality.

var EmailReportCardToParent = function(obj) {
  this.obj = obj
  this.decorate()
  return obj
};

EmailReportCardToParent.prototype = _.extend(EmailReportCardToParent.prototype, {

  // specify the method that you want to decorate
  methodToDecorate: 'saveReportCardAsPDF',

  decorate: function() {
    var self = this

    // store the original function for use in a closure
    var originalFn = this.obj[this.methodToDecorate]
    
    // define the decorated function, which captures the originalFn in its closure
    var decoratedFn = function(html) {
      // call the decorator method with the result of the originalFn as the argument
      var res = originalFn(html)
      self.sendPdfAsEmail(res)
      return res;
    };
    
    // override the method on the object with the new decoratedFn
    this.obj[this.methodToDecorate] = decoratedFn
  },

  sendPdfAsEmail: function() {
    // some actions here to
    // send email to parent
  }

});

// Example usage
new EmailReportCardToParent(new GenerateReportCard())).run()

One key goal of the Decorator pattern is that the returned object is the same object as the input object—both in terms of identity and API—but with an altered property. So the following should be true if the object is decorated properly:

var generateReportCardService = new GenerateReportCard()
var decoratedService = new EmailReportCardToParent(generateReportCardService)

// returned object is exact same object
decoratedService === generateReportCardService // true

With this pattern in practice, we can layer on any number of Decorators that decorate any number of methods on the original Service Object:

new EmailReportCardToParent(new PrintReportCard(new GenerateReportCard(student))).run()

Testing

When testing a Decorator, it is wise to test that the method is both decorating the original object properly and that the auxiliary method (or methods) are performing the right actions. A reasonably comprehensive test suite for the EmailReportCardToParent Decorator above could look like this:

var chai = require('chai')
var expect = chai.expect
var sinon = require('sinon')
chai.use(require('sinon-chai'))

describe('EmailReportCardToParent', function(){
  var generateReportCard
  var decorated
  
  before(function(){
    generateReportCard = new GenerateReportCard()
    decorated = new EmailReportCardToParent(generateReportCard)
  })

  it('returns the original object', function(){
    expect(decorated).to.be.generateReportCard
  })

  it('calls the original method', function(){
    var originalDecoratedFn = sinon.spy(
      generateReportCard, 
      EmailReportCardToParent.prototype.methodToDecorate)
    decorated.run()
    expect(originalDecoratedFn).to.have.been.calledOnce
  })

  it('calls the decorator method with the result of the original method', function(){
    var decoratorMethodFn = sinon.spy(
      EmailReportCardToParent.prototype, 
      'sendPdfAsEmail')
    decorated.run()
    expect(decoratorMethodFn).to.have.been.calledOnce
  })

  describe('#sendPdfAsEmail', function(){
    // any tests for the decorator method itself
  })
  
})

Conclusion

Decorators are useful when you want to layer on functionality to existing operations without modifying those operations for all scenarios. This means greater code portability and reuse, which is always valuable.

This concludes the series on 7 Patterns for Refactoring JavaScript Applications. I hope these concepts have provided you with new ideas of ways in which you can refactor your own applications. These techniques are just a small glimpse at how object-oriented techniques can help with code cleanliness, readability, and testability.

What are some of your favorites of the patterns I’ve covered here? Are there others that I didn’t mention that you’ve used?

The post was originally written for the Crush & Lovely Blog in 2012 and has been lovingly brought up-to-date for Engine Yard by Michael Phillips, the original author. Special thanks to Justin Reidy and Anisha Vasandani for help with the original.

About Michael Phillips

Michael was born in Portland, Oregon but spent a decade living and working in New York City. With experience working on product teams as well as with consulting companies, he has worked on web and mobile applications ranging from greenfield startups to large corporations. He is most interested in client-side JavaScript application development, but also loves learning about engineering leadership, programming culture and best practices, and client relationship management. Michael lives in Denver, Colorado with his wife Alison and currently works for Quick Left.