Certain techniques which make code more maintainable
Oct 31, 2025
While contributing to libkiwix. I learned about a few techniques from the maintainers which made code more maintainable.
When are variables justifed?
Only when they increase the readability.Not all variables increase readability.
Example 1
return "http://" + addresses.addr + suffix;
and
std::string result = "http://";
result = result + addresses + suffix
return result
Here the result variable adds no readability. Infact it decreases it.
Example 2
std::string serverUrl;
if (port == HTTP_DEFAULT_PORT) {
serverUrl = host + root;
} else {
serverUrl = host + ":" + std::to_string(port) + root;
}
return serverUrl;
and
if (port == httpDefaultPort) {
return "http://" + host + root;
} else {
return "http://" + host + ":" + std::to_string(port) + root;
}
In both the examples, the second code looks more readable.
Though this mostly applies to simple functions.
Declaring const variables wherever possible.
I advise you to start practising defensive programming. A powerful technique is to declare
constwhatever can be declaredconst, which protects you against carelessly modifying things that are supposed to be immutable.
C way of defining constants vs the C++ way
#defines are the old C-style way of declaring constants. Better use aconst int