A Cleaner Code Case Study

Sep 11th, 2020

I recently had a situation at work where a coworker tried to modify a JavaScript function I wrote, but ended up introducing some bugs. In reviewing their code, it seemed their issue was not fully understanding what the function was doing, but I believe it was my fault because the function was, frankly, poorly written.

Sometimes we have deadlines, and, in order to meet them, we may leave things a mess. I had plans to revisit it, but of course other things took priority. Now that the function was back knocking on the door, I saw an opportunity to fix it.

Often when we share our code with the world, we share our most meticulously maintained material. That is not the reality of a business all the time. At the end of the day, the product and the customers that use it are the priority. When it comes to deadlines vs perfectly clean code, the deadline wins. However, when we get the chance to go back and clean up after ourselves, we should take those opportunities because it's important we balance production with our capacity to continue producing.

I'm going to attempt to remedy the diseased function in steps in order to give you an example of how I go through the process of improving code.

The original code

Let's now look at the original function that gave my fellow developer problems.

1function valid(field, visibleField) {
2 var state = {
3 saved: true,
4 requirements: {
5 Description: {
6 required: true,
7 maxlength: 150
8 },
9 DueDate: {
10 date: true
11 },
12 PriorityID: {},
13 TypeID: {}
14 }
15 };
16 
17 if (!state.requirements[field.name]) {
18 return true;
19 }
20 
21 var errorField = visibleField ? visibleField : field;
22 
23 // required
24 if (state.requirements[field.name].required) {
25 if (field.tagName.toLowerCase() == 'input' && field.value.length == 0) {
26 errorField.classList.add('inputBorderError');
27 return false;
28 } else if (field.value === undefined || field.value === '') {
29 errorField.classList.add('inputBorderError');
30 return false;
31 }
32 }
33 
34 // max length
35 if (state.requirements[field.name].maxlength) {
36 if (field.value.length > state.requirements[field.name].maxlength) {
37 errorField.classList.add('inputBorderError');
38 return false;
39 }
40 }
41 
42 // date
43 if (state.requirements[field.name].date) {
44 if (!moment(field.value, ['MM/DD/YYYY', 'YYYY-M-D'], true).isValid()) {
45 errorField.classList.add('inputBorderError');
46 return false;
47 }
48 }
49 
50 errorField.classList.remove('inputBorderError');
51 return true;
52}

Let me also provide some simplified HTML so you can see a sample of the function's usage.

1<form id="myForm">
2 <div>
3 <input
4 name="Description"
5 type="text"
6 oninput="
7 if (valid(this)) {
8 edit(this);
9 }
10 "
11 >
12 </div>
13 
14 <div>
15 <input
16 name="DueDate"
17 type="text"
18 oninput="
19 if (valid(this, document.getElementById('myForm'))) {
20 edit(this);
21 }
22 "
23 >
24 
25 </div>
26 
27 <button type="submit">Submit</button>
28</form>

The function is decently complex, so let's go over it to make sure we understand what's happening. We have a valid() function that takes in the parameters field and visibleField. This is used within the context of an HTML form, so the two parameters are HTML elements. We see a variable immediately declared called state. It has a saved property and a requirements property.

One of the immediate issues you may notice is that the saved property in state isn't even used. Instead of confusing you by explaining it's original purpose, let's just accept that the there was a plan for it on initial development that was since abandoned, making the saved property an artifact of an old design (it never was cleaned out).

The keys in the requirements property in the state object are mapped to field names in the form (Description and DueDate are in our HTML form). The requirements properties' values, which are objects, map to different validations we want to perform on the field. For example, if we have...

1// ...
2requirements: {
3 Description: {
4 required: true,
5 maxlength: 150
6 },
7 // ...
8}

...our max length if-block catches it and returns false if it fails.

1// max length
2if (state.requirements[field.name].maxlength) {
3 if (field.value.length > state.requirements[field.name].maxlength) {
4 errorField.classList.add('inputBorderError');
5 return false;
6 }
7}

We can also see that the function handles displaying the error by adding a class to an element (errorField.classList.add('inputBorderError')). If a visibleField element is provided, that is what the error is displayed on, otherwise it uses the primary field element.

If the field passes through all of the validation rules that apply to it without returning false, the function eventually returns true, so the function always returns a boolean.

Now that we have a basic understanding of how this function works, let's clean it up.

Refactoring

Note: Before we continue, I invite you to make an attempt at improving this function on your own. Feel free to share your solution in the comments along with details of why you did what you did—it might be better than mine!

First, let's start with something easy. As I said earlier, the saved property in state is no longer a part of the solution, so let's remove that.

1function valid(field, visibleField) {
2 var state = {
3 // saved: true,
4 // ...
5 };
6 // ...
7}

Second, I don't like that this function is handling the displaying of errors when the validation fails. That's an "invisible" side-effect that makes this function deceptive, and something we should try to avoid as much as possible. Nobody would know that this function does that unless they read the contents of the function, which someone shouldn't need to do every time they need it. The function is called valid, not validateAndDisplayErrors. It's also an extra responsibility, and we want our functions to be focused. Let's remove the error handling altogether.

1function valid(field) {
2 var state = {
3 requirements: {
4 Description: {
5 required: true,
6 maxlength: 150
7 },
8 DueDate: {
9 date: true
10 },
11 PriorityID: {},
12 TypeID: {}
13 }
14 };
15 
16 if (!state.requirements[field.name]) {
17 return true;
18 }
19 
20 // required
21 if (state.requirements[field.name].required) {
22 if (field.tagName.toLowerCase() == 'input' && field.value.length == 0) {
23 return false;
24 } else if (field.value === undefined || field.value === '') {
25 return false;
26 }
27 }
28 
29 // max length
30 if (state.requirements[field.name].maxlength) {
31 if (field.value.length > state.requirements[field.name].maxlength) {
32 return false;
33 }
34 }
35 
36 // date
37 if (state.requirements[field.name].date) {
38 if (!moment(field.value, ['MM/DD/YYYY', 'YYYY-M-D'], true).isValid()) {
39 return false;
40 }
41 }
42 
43 return true;
44}

That allowed us to get rid of our second parameter, making our function that much simpler.

Third, while we are removing responsibilities, let's remove another one. For some reason this function is hard-coding an object that holds the validation rules for one specific form with our state variable. Let's remove that and make each function call pass the validation rules in for that element. Unfortunately, that means adding a second parameter back in.

1function valid(field, validationRules) {
2 
3 if (validationRules === undefined || validationRules === '')
4 return true;
5 
6 // required
7 if (validationRules.required) {
8 if (field.tagName.toLowerCase() == 'input' && field.value.length == 0) {
9 return false;
10 } else if (field.value === undefined || field.value === '') {
11 return false;
12 }
13 }
14 
15 // max length
16 if (validationRules.maxlength) {
17 if (field.value.length > validationRules.maxlength) {
18 return false;
19 }
20 }
21 
22 // date
23 if (validationRules.date) {
24 if (!moment(field.value, ['MM/DD/YYYY', 'YYYY-M-D'], true).isValid()) {
25 return false;
26 }
27 }
28 
29 return true;
30}

So now our usage looks like this:

1<input
2 name="DueDate"
3 type="text"
4 oninput="
5 if (valid(this, {date:true})) {
6 edit(this);
7 }
8 "
9>

Fourth, one thing that's bugging me now is the function being dependent on the HTMLElement interface. That's not good for testing, and it's an unnecessary dependency because the field is no longer being used to handle errors. We are wrestling with different tag types in some instances in order to ultimately get the element's value, so let's just pass the value in directly and rid ourselves of that cumbersome burden.

1function valid(value, validationRules) {
2 if (
3 (typeof validationRules === 'object' && Object.keys(validationRules).length === 0)
4 || validationRules === undefined
5 || validationRules === ''
6 ) {
7 return true;
8 }
9 
10 // required
11 if (validationRules.required) {
12 if (!! value)
13 return false;
14 }
15 
16 // max length
17 if (validationRules.maxlength) {
18 if (value.length > validationRules.maxlength)
19 return false;
20 }
21 
22 // date
23 if (validationRules.date) {
24 if (!moment(value, ['MM/DD/YYYY', 'YYYY-M-D'], true).isValid())
25 return false;
26 }
27 
28 return true;
29}

This function has improved dramatically from when we started. If you stopped here, you could feel pretty confident in trusting it to accomplish what it needs to. I'm going to take it a little further though.

Fifth, these if-statement blocks feel primitive. I think we can do better. They lack clarity and readability. Instead what I want to do is break these "validators" out into their own functions so that if we want to edit one or add to them, we only need to modify a small part. This allows us to leave our main function that performs the validation alone.

The thought process I'm describing is derived from the SOLID principles. The O in SOLID is the Open-Closed Principle—open for extension, closed for modification. That means we want to make it easy to extend our validation function by being able to add validators without modifying the existing code. It's also the S for Single Responsibility Principle because we are breaking our one big function down into smaller immutable methods that have only a single reason to change.

I still want to keep the function self-contained; see if you can follow what I'm going to do. I want to keep my validator methods within the valid function. Let's pull our validators into their own methods in a local object validators.

1function valid(value, validationRules) {
2 var validators = {
3 required: function(value, parameter) {
4 if (!! value)
5 return {rule:'required', message:'This field is required.'};
6 
7 return false;
8 },
9 
10 maxlength: function(value, parameter) {
11 if (value.length > parameter)
12 return {rule:'maxlength', message:'Maximum length is ' + parameter + ' characters.'};
13 
14 return false;
15 },
16 
17 date: function(value, parameter) {
18 if (!moment(value, parameter, true).isValid())
19 return {rule:'date', message:'Not a valid date format, must match ' + parameter + '.'};
20 
21 return false;
22 }
23 };
24 
25 // ...
26}

We updated the validators to each return an error object with the rule that failed and a default message the user may want to display. Since we aren't handling the errors in-house anymore, we want to hand back the most information we can that gives the most flexibility to the user. There is a difference between the function doing work that has invisible side-effects and returning data that doesn't do any work on its own.

Sixth, let's rework the logic that checks if our value is valid or not based on the validation rules.

1function valid(value, validationRules) {
2 var validators = {
3 //...
4 };
5 
6 // bug fix here
7 if (validationRules.required === undefined && !value)
8 return [];
9 
10 var errors = [];
11 var result;
12 for (var rule in validationRules) {
13 result = validators[rule](value, validationRules[rule]);
14 if (result) errors.push(result);
15 }
16 
17 return errors;
18}

Now our valid function returns an array instead of a boolean—it will return an empty array if there are no errors, or an array of our error objects that failed validation.

While rewriting this part I found a bug—if the validationRules parameter doesn't include a required property, then we shouldn't bother checking the other rules when the value is empty. I labeled the fix above with the "bug fix here" comment.

To process our rules, we simply loop through the properties of the validationRules parameter and invoke the corresponding validator. If the result that comes back evaluates to true (because it's an object when validation fails), then we push it into the errors array.

Note: I'm aware there are a lack of catches for handling potential issues such as using a non-existant validator in the validationRules, but I want to keep the example straightforward for learning purposes.

Seventh, you may be thinking "Hey, every time you call this function you are re-defining every validator method!" Great catch if you did! It's inefficient to ask the valid() function to define the validators object with all of its methods every time the function is called, so I'm going to turn valid into a variable and assign it to an immediately-invoking, anonymous function that returns a closure. This keeps the validators in the local scope, creates them only one time, and allows me to continue using valid the same way.

1var valid = (function() {
2 var validators = {
3 required: function(value, parameter) {
4 if (!! value)
5 return {rule:'required', message:'This field is required.'};
6 
7 return false;
8 },
9 
10 maxlength: function(value, parameter) {
11 if (value.length > parameter)
12 return {rule:'maxlength', message:'Maximum length is ' + parameter + ' characters.'};
13 
14 return false;
15 },
16 
17 date: function(value, parameter) {
18 if (!moment(value, parameter, true).isValid())
19 return {rule:'date', message:'Not a valid date format, must match ' + parameter + '.'};
20 
21 return false;
22 }
23 };
24 
25 return function(value, validationRules) {
26 if (validationRules.required === undefined && !value)
27 return [];
28 
29 var errors = [];
30 var result;
31 for (var rule in validationRules) {
32 result = validators[rule](value, validationRules[rule]);
33 if (result) errors.push(result);
34 }
35 
36 return errors;
37 };
38})();

That's going to be our final refactor. Let's see how the client utilizes our function now.

1<div id="DescriptionContainer">
2 <input
3 name="Description"
4 value="text"
5 oninput="
6 var errors = valid(this.value, {required:true, maxlength:20});
7 
8 if (errors.length) {
9 var elErrors = this.nextElementSibling;
10 
11 var messages = errors.map(error => error.message);
12 elErrors.innerHTML = errors.join('<br>');
13 elErrors.classList.remove('hidden');
14 } else {
15 elErrors.classList.add('hidden');
16 elErrors.innerHTML = '';
17 }
18 "
19 >
20 
21 <div class="errors hidden"></div>
22</div>

We now check the length of the array coming back from the function call to determine if there are any errors. If there are, we can get the element we want to display error messaging in and list the errors in it and display it.

Review

You may be thinking that the way we interact with this function became more complicated since we started, and you're right. However, our goal here was to fix up a specific function. That involves removing the other responsibilities it had that shouldn't have been there. Right now that means we moved that responsibility to the client, but that doesn't mean we can't write another function that uses our valid function to handle errors for us.

What we can do is use our new valid function as a building block for higher-level functions. If we want to have a function that intentionally has the side-effect of displaying errors, we can utilize our valid function within that. But we keep the validation part decoupled from other responsibilities, such as displaying errors.

We also reduced dependencies within the function which greatly expands the usability and flexibility of it. For example, removing our dependency on the HTMLElement interface allows us to use this function for data coming back from an AJAX call before displaying it, which wasn't possible before.

In breaking out the validators and giving each section a single responsibility, we made the function way easier to work with for our future selves and others first getting familiar with it. If we want to add a new validator method, we can see what the input and output of the others are and copy it, or look at how our main processing loop works with them to know how to implement it (In an OO language the validators would likely implement a Validator interface).

When we build a culture of high coding standards where we can assume a function named valid is only performing validation, we increase trust from the developers working with the code because they don't have to read the contents of every new function they come across to make sure there aren't invisible side-effects or other strange interactions happening. We liberate a significant amount of time and brain-power because of this. The less time spent getting reacquainted with messy, complex functions, the more time spent on better things like new features, learning new skills, and more.