Why we must not use magic numbers and hard-coding?
Magic numbers and hard-coded values explained with their maintenance and security risks, plus practical replacements using constants, enums, configuration, and read-only values.
Why we must not use magic numbers and hard-coding?
Almost every code base has few numbers and strings which are written directly in the code, if (status == 3), Thread.Sleep(5000), "http://10.0.0.15/pricing". They look harmless when we write them, because at that moment we know what they mean. After few months, nobody remembers why it is 3 or why it is 5000, and when the server IP is changed, someone has to find and replace it in many places and redeploy the application. In this article, we are going to see what is magic numbers and hard-coding, why they are dangerous and how to replace them with constants, enums, configuration and read-only values.
TL;DR Summary
- Magic number is a literal value in the code without any explanation of its meaning.
- Hard-coding is putting environment or business specific values directly in the code.
- Both reduce readability and make change risky and expensive.
- Use
constfor values which never change, i.e. mathematical or protocol values. - Use
enumfor a fixed set of related values like status codes. - Use
static readonlyfor values computed at runtime or values which may change between versions. - Use configuration (
web.config/ Azure App Settings) for environment specific values. - Never hard-code secrets like passwords and keys in the code.
Challenges
Lack of meaning
When the developer reads if (fund.Status == 3), he has to search the database or ask someone what 3 means. It slows down the reading and opens the door for wrong assumptions. Someone may think 3 is “Closed” while actually it is “Suspended”.
Same value in many places
The same magic number is usually copied in many places. When the business decides the maximum number of funds in a universe is 50 instead of 25, the developer has to find every 25 in the code. Some of them are related, some are not. Missing one place means inconsistent behaviour, changing the wrong one means a new bug.
Redeploy for every environment change
Hard-coded connection strings, URLs and file paths force us to change the code and redeploy for every environment, development, test, staging and production. It is very easy to deploy the test URL into production by mistake, which will have direct impact on our customers.
Security risk
Hard-coded passwords and API keys end up in source control, and everyone who has access to the repository has access to the production systems. Removing them later from the history is not easy.
What is a Magic Number?
A magic number is a numeric (or string) literal in the source code which has a meaning that is not obvious from the code itself.
In simple terms, if you need a comment or a person to explain what the number means, then it is a magic number.
What is Hard-coding?
Hard-coding is the practice of embedding the data, which can change, directly into the source code instead of getting it from an external source like configuration or database.
Think about a printed menu card in a restaurant where the prices are written with a permanent marker on the wall. Every time the price changes, you have to repaint the wall. Menu card with a price list that can be replaced is much easier.
Why it is important to avoid them?
In order to make the code readable, to have a single place for every value and to deploy the same build to all environments, we should replace magic numbers and hard-coded values from the beginning. It reduces the bugs, reduces the deployment risk and also it is a basic security practice.
How to replace them?
Let us discuss the options one by one with examples. Choosing the right option depends on how often the value is changing and who is changing it.
Constants (const)
Use const for the values which never change for the life of the application.
// Bad
var hours = totalMinutes / 60;
// Good
private const int MinutesPerHour = 60;
var hours = totalMinutes / MinutesPerHour;
Note:
constvalues are copied into the calling assemblies at compile time. If you change a publicconstin a shared library, all the assemblies using it must be recompiled, otherwise they keep using the old value. For values which may change between versions, usestatic readonlyinstead.
Enums
Use enum for a fixed set of related values, especially status and type codes.
// Bad
if (fund.Status == 3) { ... }
// Good
public enum FundStatus
{
Draft = 1,
Active = 2,
Suspended = 3,
Closed = 4
}
if (fund.Status == FundStatus.Suspended) { ... }
Now the code explains itself and the compiler will catch the typos.
Read-only values (static readonly)
Use static readonly when the value is fixed after startup but cannot be a compile time constant, or when it is a public value in a shared library.
public static class FundDefaults
{
public static readonly TimeSpan PriceCacheDuration = TimeSpan.FromMinutes(15);
public static readonly string[] SupportedCurrencies = { "EUR", "USD", "GBP" };
}
Configuration
Use configuration for the values which are different between environments or which the operations team need to change without a new build, i.e. connection strings, service URLs, timeouts, feature switches.
<appSettings>
<add key="Pricing:ServiceUrl" value="https://<pricing-host>/api/prices" />
<add key="Pricing:TimeoutSeconds" value="30" />
<add key="Universe:MaxFunds" value="50" />
</appSettings>
Don’t read the ConfigurationManager everywhere in the code, wrap it in a settings class and inject it, so it is easy to test.
public interface IPricingSettings
{
string ServiceUrl { get; }
int TimeoutSeconds { get; }
}
public class PricingSettings : IPricingSettings
{
public string ServiceUrl
{
get { return ConfigurationManager.AppSettings["Pricing:ServiceUrl"]; }
}
public int TimeoutSeconds
{
get { return int.Parse(ConfigurationManager.AppSettings["Pricing:TimeoutSeconds"]); }
}
}
Use Web.config transformations (Web.Release.config) or the App Settings in Azure App Service to override the values per environment. In Azure App Service, the App Settings configured in the portal override the values in web.config at runtime, so the same package can be deployed to all slots.
Secrets
Never put passwords, keys and connection strings with credentials in the code or in the web.config committed to source control. Keep them in the App Settings / Connection Strings of Azure App Service or in a separate config file which is excluded from source control.
<appSettings file="secrets.config">
</appSettings>
Which one to use?
Find below the quick summary,
| Value type | Example | Use |
|---|---|---|
| Never changes | Minutes per hour, HTTP status 404 | const |
| Fixed set of options | Fund status, fund type | enum |
| Fixed at runtime, may change in new version | Default cache duration | static readonly |
| Changes per environment | Connection string, service URL | Configuration |
| Changes by business users often | Fee percentage, max funds in universe | Database / admin screen |
| Secret | Password, API key | Secure configuration, never source control |
Note: Not every literal is a magic number.
0,1,string.Emptyin obvious places likefor (var i = 0; ...)orcount + 1are fine. Don’t createconst int One = 1;, it adds noise and no meaning.
Wrap up
In this article, we have looked at what is magic numbers and hard-coding, the problems they create and how to replace them with constants, enums, read-only values and configuration. Thanks for reading this article. In the next article, I will walk you through what is a God object and how to break it by refactoring.
Related Posts
Code review checklist for .NET teams
A practical .NET code review checklist covering design, readability, correctness, errors, security, performance, testing, operations, and constructive review comments and discussion.
What is a God object and how to break it?
God objects explained through their warning signs, causes, and a step-by-step refactoring approach using characterization tests, extraction, interfaces, and dependency injection.
Why we need Clean Code?
Why clean code matters, what makes code clean (meaningful names, small functions, guard clauses, comments that explain why) and how to bring the practice into your team.