Posted on ::

Better for you, the programmer, and anyone else that is going to read it afterwards. Entire books have been written on this subject, so I will focus on just one example. Take the following problem:

Return Largest Numbers in Arrays Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays. Read the full problem here

Solution A

function largestItem(arr) {
  let max = arr[0];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > max) max = arr[i];
  }
  return max;
}

function largestOfFour(arr) {
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    result.push(largestItem(arr[i]));
  }
  return result;
}

Solution B

function largestOfFour(arr) {  
  let result = [];
  for (let i = 0; i < arr.length; i++) {
    let max = arr[i][0];
	for (let j = 0; j < arr[i].length; j++) {
	  if (arr[i][j] > max) max = arr[i][j];
	}
	result.push(max);
  }
  return result;
}

In solution A we first break down the problem in two areas:

  1. How to find the largest number in an array.
  2. How to make a new array with the numbers we found in (1).

This helps us manage the scope of the problem we focus on at any given time.

In solution B we tackle the whole problem in one go, resulting in common issues such as:

  1. Which for loop does what? it's hard to see at a glance.
  2. Should max be initialized inside or outside the first loop?
  3. Keeping your indices i and j where they need to be can be hard and error prone.
  4. You can't easily re-use the logic to find the largest number for other problems.

My argument here is that thinking about structuring your code is also part of breaking down the problem in manageable chunks, and vice-versa. You're likely to spend less time trying to figure out what your code is doing if you spend a bit of time thinking about structure up front.

And even if you don't come up with a good structure that fits your problem up front, you can always make it better later, we even have a word for it: Refactoring and some famous programmers wrote books about it :).

That's it for today, I hope you found this useful, and in any case I would greatly appreciate your feedback! Feel free to dm me with any comments, questions or corrections.

Table of Contents