Hard-coding For Beginners

What is Hard-coding

Hard-coding refers to the practice of embedding specific values or data directly into the source code of a program or application instead of using a more flexible and dynamic approach.

This includes writing and using values directly in the code, typically by assigning them to variables or using them in calculations or comparisons.

Why Hard-coding Should not be Used to Answer Coding Questions

While hard-coding may provide a quick and simple solution in certain situations, it has several drawbacks. One of the main disadvantages is the lack of flexibility. Hard-coded values are rigid and fixed, making it difficult to modify or adapt the program without changing the source code. Any changes to the values require manual code modifications, recompiling, and redeploying the application.

What Is An Example of Hard-coding

function addTwoNumbers(x, y) {
  return 5 + 10;
}

The addTwoNumbers function above will always return 15 as it does not use its inputs to return the correct answer.

While the multiplyTwoNumbers below will only the return the correct product if a is 1 and b is 2, or a is 2 and b is 3.

function multiplyTwoNumbers(a, b) {
   if (a == 1 && b == 2) {
      return 2;
   } else if( a == 2 && b == 3) {
      return 6;
   } 
   // And so on
}

Hard-coding May Delay Your Learning

The point of trying to write code is to solve problems. If you attempt to short-circuit this process by hard-coding the testcases for example, you will not gain the skills needed to write flexible code that works for any input. You will also fail to learn how to write usable code in the real world where there are many possible problems to solve.

When Should You Hard-code

There is a time and place for hard-coding though. For example, when you need to quickly debug your logic or your solution. Say that you’re writing a recursive function and you want to test it, you can hardcode some test-cases to confirm it is working. Or if you are writing code that relies on apps that you do not control, you can test your code with hard-coded responses just to confirm that it works as you would expect.

To conclude, here’s a joke you may enjoy (credit: @plamoni):

  • Knock knock.
  • Who’s there?
  • 472
  • 472 who?
  • 472
  • What?
  • 472
  • I don’t get this joke…
  • 472
  • Wait, did you just hard-code your solution to always respond 472?
  • 472
6 Likes