In general, I like things that are functional before they’re beautiful. I’m not making some kind of clever programming pun; it’s purely a function over form mindset. If my projector is throwing an image a little too low, I’ll put a coaster underneath the front. Does everything now work the way I want? Yes.

Was that the best way to solve the problem? Absolutely not.

I tend to write my code the same way. I have a set of problems to solve, and I solve them one after another until the project is complete and in proper working order. I’ve also always finished my projects early; now I’m beginning to spend some time looking back and how I accomplished my goals, and how I could have done it better.

Room For Improvement

I’ve recently been reading Eric Elliot’s wonderful 2 Pillars Of Javascript series. He goes into detail with the value of pure functions, reducing coupling, and OLOO theory. As I’m stepping back and taking a deeper look at my own code, these are not principles that I’ve been following well.

For one of my projects, I needed a random number from 0-10, and I need a new random number from 0-10 multiple times throughout the app. Consider the following code:

var rng;
function chooseRNG() {
     rng = Math.floor(Math.random() * 11);
     console.log("My super secret number is " + rng);

This code fully provides the desired result. I can repeat the function call whenever I want and claim DRY code (Don’t Repeat Yourself). The problem is that this will only ever work in a single case – whenever I want to randomize the value of rng.

Instead, consider the following updated code:

var rng = chooseRNG();
function chooseRNG() {
     randomNum = Math.floor(Math.random() * 11);
     console.log("My super secret number is " + randomNum);
     return randomNum;

The function is now pure; it doesn’t alter any global variables, stored data, or any other content outside of its own encapsulation. It will now be able to randomize any variable I choose, making it significantly more flexible. And I have the added freedom of being able to call my variables wherever I want in the code; since the functions will be hoisted to the top, I don’t need to make sure my rng variable has been initialized before the function is called.

This blog is about honestly and openly grappling with my frustrations, and exposing the process improvements that occur as a result. I’m excited to have a new focus on SOLID coding techniques moving forward!