The Art of Using Constants
Constants are values that remain unchanged throughout the execution of a program.
One major difference between a good developer and a bad developer is the use of constants in their code.
Good developers always make good use of constants in their code, so that the code is more readable, maintainable and less error-prone. However, for beginners, such subtleties are often overlooked.
Enforcing Immutability
If you are working with a variable that should not change its value during the execution of the program, you should always declare it as a constant.
The benefit of using constants is that it helps enforce immutability, and avoid accidental changes to the value, which can lead to bugs and unexpected behavior.
For example, in JavaScript, you can use the const
keyword to declare a constant, and the value of the constant cannot be reassigned, otherwise, it will throw an error.
// Bad
let my_name = 'Alice'
console.log(`Hello, my name is ${my_name}`)
In this example, let's say I would never want to change the value of my_name
throughout the execution of the program. As we used let
keyword above, the value of my_name
can be reassigned elsewhere accidentally in the code, which can lead to bugs and unexpected behavior.
// Good
const MY_NAME = 'Alice'
console.log(`Hello, my name is ${MY_NAME}`)
If we use const
keyword, we can't reassign the value of MY_NAME
throughout the execution of the program. And if we try to reassign the value of MY_NAME
, or if the value is accidentally changed elsewhere in the code, it will throw an error.
It is also notable that, in JavaScript, some styling guides may suggest to name constants in all uppercase letters, with words separated by underscores.
Avoiding Magic Numbers
Magic numbers are hard-coded numerical values scattered throughout your code without any clear meaning or explanation. They make your code difficult to understand and maintain.
By replacing these magic numbers with meaningful constants, you can significantly enhance the readability and maintainability of your code.
// Bad
function calculateArea(radius) {
return 3.14 * radius * radius
}
// Good
const PI = 3.14
function calculateArea(radius) {
return PI * radius * radius
}
In the above example, the constant PI
is used to represent the mathematical constant π.
In other cases, you would use constants to represent things like configuration values, error codes, or any other value that should not change during the execution of the program.
And by naming the constants with a clear and descriptive name, you could make your code more self-explanatory, and easy to understand for other developers.
Using Constants for User and Error Messages
Another area where constants can be invaluable is when dealing with user messages and error messages.
Instead of hard-coding these messages directly into your code, it is best practice to define them as constants. This approach offers several benefits, including improving maintainability, and ensuring consistency across your application.
// Bad
function validateEmail(email) {
if (!email.includes('@')) {
throw new Error('Invalid email address')
}
}
// Good
const ERROR_MESSAGE_OF_INVALID_EMAIL = 'Invalid email address'
function validateEmail(email) {
if (!email.includes('@')) {
throw new Error(ERROR_MESSAGE_OF_INVALID_EMAIL)
}
}
In more advanced scenarios, you could even use constants to manage internationalization and localization in your application. By defining all your user-facing messages as constants, you can easily swap them out for different languages or locales.
One approach is to have one JSON file for each language, where each key-value pair represents a constant and its corresponding message.
// en.json
{
"ERROR_MESSAGE_OF_INVALID_EMAIL": "Invalid email address"
}
So that you can easily switch between languages by loading the appropriate JSON file.
Conclusion
The art of using constants is a fundamental skill that every developer should master.
By mastering the art of using constants, you could level up your coding skills and become a better developer that writes more robust, readable and maintainable code.