7 Steps to Better Javascript
JavaScript libraries like jQuery have empowered Web developers to create very complex Web interactions and animations in the browser using simple syntax and few lines of code. Unfortunately, it is also easier than ever to write JavaScript code that is untestable while being difficult to read, extend and maintain.
I will be walking you through a demonstration of seven key steps you can take right now in your own JavaScript code to make it more legible, testable and easy to maintain over time.
Before We Begin...
Download the source code from Github:
git clone git://github.com/chrisjpowers/js_refactoring_demo.git
Please view the README for instructions on getting the app up and running. NOTE: There is a separate Javascript file for each refactoring so that you can clearly see how each step affects the code.
Our Problem
Despite being a very simple, functional app with only 40 lines of Javascript, this code could still use some work:
- The code lacks legibility -- a reader would probably be lost if it weren't for the code comments.
- Because all of the code is wrapped up in anonymous functions, these functions cannot be unit tested.
- Logic for different display items is scattered throughout, which makes it difficult to update the code.
- While it would certainly be possible to add features and make changes to this codebase, each change would bring additional confusion and code-debt. The goal of refactoring is to bring clarity to the code so that future changes can bring further clarity.
Our Goals
We want to refactor this code in order to...
- Increase legibility, and subsequently maintainability.
- DRY up code to remove duplication and increase maintainability.
- Make the code testable and build a test suite.
Our 7 Steps (Refactorings)
- Modularize and Namespace Chunks of Logic
- Extract Anonymous Callbacks into Named Functions
- Extract Inline Business Logic into Individual Functions
- Move Logic to the Proper Object
- Introduce Event Broadcasting
- DRY Up Constant Values
- Reuse Objects with Extensible Setup Params
Glossary
- DRY: "Don't Repeat Yourself" - it refers to code and practices that are intentional about reusing code and keeping logic consolidated into a single place.
- Refactoring: A technique where the programmer makes changes to the codebase that have no affect on a user's experience, but rather improves the quality and legibility of the codebase. DRYing up code could be an example of refactoring.