Hard-Coding: What Does It Mean? and Is It a Bad Practice?

Avoid Hard-Coding While Building a Simple Student Grade Calculator (Updated)

Hard-Coding: What Does It Mean? and Is It a Bad Practice?

Hard coding (also hard-coding or hardcoding) is the software development practice of embedding data directly into the source code of a program or other executable object, as opposed to obtaining the data from external sources or generating it at runtime. - Wikipedia

Yeah. That's it. What you just read above is exactly what hard-coding means.

Put simply: Hard-coding is when you fix a value for a variable directly inside your code (or source code).

Okay! Here is a practical case of hard-coding.

If you had followed along while we (me and my frequent readers) created the simple student grade calculator, you would already have the source code below:

# a dictionary
student = {
    "maths": 10,
    "english": 30,
    "programming": 50,
    "accounting": 40
}

# an empty list that will contain the student's mark
student_marks = []

# the iteration
for score  in student.values():

    #the collection
    student_marks.append(score)

# get the sum of scores
total_score = sum(student_marks)

# get the average score
average = total_score / len(student_marks)

# check if the average score is below/ above 50 to give remark
if average < 50:
    remark = "FAIL"
else:
    remark = "PASS"

# print out the information for the student parent to see ๐Ÿ˜
print("Student's result:")
print(f"Total: {total_score}; Average: {average} %; Remark: {remark}")

Want to know how we arrived at this code? See the full article here.

Now I want you to look at the source code very well. Where in the code did we fix a value for a variable? Or to rephrase, which variable already has a fixed value in the code?

# a dictionary
student = {
    "maths": 10,
    "english": 30,
    "programming": 50,
    "accounting": 40
}

Yes, the student dictionary is that variable that has a fixed value. It contains the grades of a single student during a semester.

The value for the student dictionary can not be changed. So In a case where we have multiple students in an institution, we would have to go into our source code and change the values in the student dictionary by ourselves.

I think with what has been said you can agree that it is not a good practice.

However, do note that there are some cases where hard-coding is required and these cases are usually when the value for the variable does not need to be changed. It needs to be a fixed value.

As you grow in your programming career, you will come across such cases.

So we have established the fact that hard-coding the value for the student dictionary is a bad practice in this program.

How can we correct this? Here comes the Python input() function.

The Python input() function is used to accept inputs from users there by generating data at runtime (when we run the code).

Let's use it to rewrite the student dictionary as follows:

# first we ask the user to input the student's scores
print("Please enter the student scores for the subjects below:")

# save the user input for the appropriate subject
maths = int(input("Maths: "))
english = int(input("English: "))
programming  = int(input("Programming: "))
accounting = int(input("Accounting: "))

Explanation: We ask the user, probably a lecturer or teacher, to input an individual student's scores for all the subjects. We save the input we receive in a variable that has the same name as the subjects (i.e the variables maths, english, accounting and programming)

Then:

# we assign the variables to their appropriate subject in the dictionary
student = {
    "Maths": maths,
    "English": english,
    "Programming": programming,
    "Accounting": accounting
}

Explanation: We then assign the variables to their appropriate key (subject) in the student dictionary.

Alright then, the student dictionary has been 'un-hard-coded' (if there is such a thing as that ๐Ÿ˜)

Let's try it out. Save your code and run it...

...

Oh, wait! Find the complete adjusted code below:

# first we ask the user to input the student's scores
print("Please enter the student scores for the subjects below:")

# save the user input for the appropriate subject
maths = int(input("Maths: "))
english = int(input("English: "))
programming  = int(input("Programming: "))
accounting = int(input("Accounting: "))


# we assign the variables to their appropriate subject in the dictionary
student = {
    "Maths": maths,
    "English": english,
    "Programming": programming,
    "Accounting": accounting
}


# an empty list that will contain the student's mark
student_marks = []

# the iteration
for score  in student.values():

    #the collection
    student_marks.append(score)

# get the sum of scores
total_score = sum(student_marks)

# get the average score
average = total_score / len(student_marks)

# check if the average score is below/ above 50 to give remark
if average < 50:
    remark = "FAIL"
else:
    remark = "PASS"

# print out the information for the student parent to see ๐Ÿ˜
print("====================")
print("Student's result:")
print(f"Total: {total_score}; Average: {average}%; Remark: {remark}")

So copy, save it and run it.

Expected output:

>>> Please enter the student scores for the subjects below:
>>> Maths: 70
>>> English: 70
>>> Programming: 70
>>> Accounting: 10
>>> ====================
>>> Student's result:
>>> Total: 220; Average: 55.0%; Remark: PASS

Okay!

We are done now. Everything is working just fine.

For the curious minds: if you are curious about cases where hard-coding is useful, click on this link here

Make sure to read all comments especially the second one. Also, remember to come back to this article, I'm not done with you yet ๐Ÿ˜‰.

To conclude this article, let's talk briefly about the usefulness of our code.

You may have noticed that our code has only one student dictionary. The effect of this is that we can only compute the grade of just one student at a time.

This is a very crude way to write a program.

How do we make adjustments in our code to allow multiple student grade computation?

Oh, so you are thinking of doing something similar to this:

student_1 = {
    "Maths": maths,
    "English": english,
    "Programming": programming,
    "Accounting": accounting
}

student_2 = {
    "Maths": maths,
    "English": english,
    "Programming": programming,
    "Accounting": accounting
}

student_3 = {
    "Maths": maths,
    "English": english,
    "Programming": programming,
    "Accounting": accounting
}

# the line below is not a python code ๐Ÿ˜
student_(n+1) where n is the number of students and so on ...

So if there are say, 1000 students, you'd write a thousand dictionaries for them, right? Cool!

This is against the DRY Principle in programming

What does the DRY Principle mean? and how can we follow it when writing codes?

I am currently writing an article about it and I will show you how to use it in our student grade calculator program

Subscribe to my newsletter to be notified once the article is ready for your consumption ๐Ÿ˜‰.

Thanks for reading. Do leave a comment, a reaction, or even share this article with others if you found it interesting and informative. I do put in serious efforts to write articles like this.

Please find the subscription form either above or below this write-up.

See ya later! ๐Ÿ‘‹

Photo by Chris Ried on Unsplash

ย