JavaScript affords us so much flexibility that we can sketch up a program in minutes. Sketching is excellent for trying out new concepts or experimenting with new techniques. However, when we are trying to produce scalable and reliable software, sketching often produces unmaintainable spaghetti code. I propose a simple structure called Systematic Development through three stages of Plan, Build, and Test to create reliable software. Systematic Development applies to all programming languages but I will focus on how to use this structure in JavaScript.
I will illustrate the principles by creating a vector calculation library. First through a common sketching approach and then through the Systematic Development approach. The point is not to teach you how to write a vector calculation library so you don’t need to understand all the implementation details. However, I hope that a real-world project will help you understand and apply Systematic Development more easily.
Sketching Approach
A vector has an x and y component
We can add vectors
We can negate a vector
We can subtract vectors
All are good so far. However, now we want to handle not just 2d vectors but also 1d and 3d vectors. We need a total refactoring of all three functions because they assume the vectors are 2d. To detect what dimension the input vector is in, we will create three helper functions — is1d
, is2d
, and is3d
.