The code base I'm currently working on is littered with hard-coded values.
I view all hard coded values as a code smell and I try to eliminate them where possible...however there are some cases that I am unsure about.
Here are two examples that I can think of that make me wonder what the best practice is:
1. MyTextBox.Text = someCondition ? "Yes" : "No"
2. double myPercentage = myValue / 100;
In the first case, is the best thing to do to create a class that allows me to do MyHelper.Yes and MyHelper.No or perhaps something similar in a config file (though it isn't likely to change and who knows if there might ever be a case where its usage would be case sensitive).
In the second case, finding a percentage by dividing by 100 isn't likely to ever change unless the laws of mathematics change...but I still wonder if there is a better way.
Can anyone suggest an appropriate way to deal with this sort of hard coding? And can anyone think of any places where hard coding is an acceptable practice?
A best practice in technology is to not reference IDs or text directly, or “hard code” them. That same best practice applies to the declarative side as well. You should not hard code IDs or text in your formulas, validation rules, processes, flows, and so on.
Hardcoded literals should appear in unit tests for the test values, unless there is so much reuse of a value within a single test class that a local constant is useful. The unit tests are a description of expected values without any abstraction or redirection.
In Excel, it means using specific amounts in formulas or code instead of using calculated or referenced amounts. For example, if the actual amount of a sales tax is included in a formula, the tax amount is hard coded. If the formula references a cell that contains the sale tax amount, the tax amount is not hard coded.
Hard coding is when codes are assigned by the CDM without human intervention, whereas soft coding is when codes are manually assigned by a coding specialist.
The real question isn't about hard coding, but rather repetition. If you take the excellent advice found in "The Pragmatic Programmer", simply Don't Repeat Yourself (DRY).
Taking the principle of DRY, it is fine to hardcode something at any point. However, once you use that particular value again, refactor so this value is only hardcoded once.
And can anyone think of any places where hard coding is an acceptable practice?
For short anything that won't be maintained by others.
Gee I've just realized how much being maintainer coder hurt me in the past :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With