Write better code
I am currently mentoring two great guys one time per week.
One of them gets one hour and the other gets two.
For tracking my hours with them, I add up the numbers at the end of every week.
I want to write a function that adds the two numbers.
No problem at all.
function addTwoNumbers(a, b) {
return a + b;
}
const resultOfTwoNumbers = addTwoNumbers(1, 2);
console.log(resultOfTwoNumbers); // 3
The function takes two input parameters and returns the sum.
But... I know, that I will get a new mentee next week for one hour per week.
So what's about maintainability?
Okay, we can do this.
function addThreeNumbers(a, b, c) {
return a + b + c;
}
const resultOfThreeNumbers = addThreeNumbers(1, 2, 1);
console.log(resultOfThreeNumbers); // 4
What has changed?
I added one mentee's hours, and had to add it at three places (1
, c
, c
).
So for n
additional mentees, I have to add code at 3n
places.
That's not very maintainable.
Okay, we can solve this, too.
We change the args/params from three single numbers to an array.
Because we have an array, we can reduce the array's values into a sum.
function addAllNumbersFromArray(hours) {
return hours.reduce((acc, curr) => acc + curr, 0);
}
const resultOfAllNumbersFromArray = addAllNumbersFromArray([1, 2, 1]);
console.log(resultOfAllNumbersFromArray); // 4
Great work, if we want to add a mentee, we only have to add code at one place (the argument in add([])
), down from three.
The next week, Peter has successfully finished his mentoring and leaves the group.
But... what is Peter's number?
Okay, I know that he's my second mentee.
But is this very maintainable? Using my own memories to "guess" about it?
What will happen, if I'll have 10 mentees?
function addAllNumbersFromObject(hours) {
return Object.values(hours).reduce((acc, curr) => acc + curr, 0);
}
const hours = {
adam: 1,
paula: 1,
};
const resultOfAllNumbersFromObject = addAllNumbersFromObject(hours);
console.log(resultOfAllNumbersFromObject); // 2
Because it's easier for me to remember the mentee's name instead of the mentee's rank of entering the list, I change the array into an object.
Then I go over the object's values and reduce them into a sum.
I can easily add and remove a mentee's name and his/her hours.
In addition, I can also access the data of a specific person directly, just by knowing their name (hours[name]
).
Next
If you want to make this code better, think about upcoming challenges if the user doesn't input a number:
const hours = {
sarah: "not a number",
bill: null,
};
if else
?
.filter()
?
Thinking about it
If I send this code to another person, he only has to add his hours to the variable hours
. No thinking about the add
function, its input or something else. All this is already abstracted for the reader.
No cognitive overload, more time for doing useful stuff.
Every beginner can add or remove hours.
Top comments (0)