Since I started working in this industry, I often hear words that I can't hear every day, but today I heard the word "hard coding" and didn't understand the meaning, so I will output the results of my research. I will.
I mainly referred to this article. IT Glossary that makes you feel like you understand even if you don't understand it
As mentioned in the article, in a nutshell, it is "embedding the processing and values that should be separated separately in the source code".
It is easy to understand if you look at a specific program.
sample.rb
price = gets
puts price + price * 0.1
The above is a very simple Ruby script that receives the price of an item as standard input and displays the tax-included price with a consumption tax rate of 10%. In the program, the consumption tax rate of 0.1 is written directly in the place where the tax-included price is calculated. The person who wrote this script knows that it is a program that displays the tax-included price, so there is no problem, but what is 0.1 when others see it? It is difficult for others to understand the meaning of the program. Hard coding is the process and value (tax rate this time) that is easier to understand if they are separated in this way. If the numbers are hard-coded, they are called "magic numbers". This tax rate of 0.1 is a magic number.
Hard-coding when developing with multiple people is generally something that should be avoided, as it can be difficult for others to see the code.
If you eliminate the hard coding of this tax-included price program, the following is an example.
sample.rb
price = gets
tax = 0.1
puts price + price * tax
By separating the consumption tax as tax, readability will be improved, and even if the consumption tax changes in the future, only the tax part needs to be changed, so it will be easier to correct. It is said that the writing method that separates processing contrary to hard coding is called soft coding.
This time it was a simple program with tax-included price display, so it is difficult to understand the gratitude for eliminating hard coding, but when it comes to a huge program, the benefits of soft coding will be great. Specifically, database settings etc. are considered to be items that should be avoided by hard coding.
Recommended Posts