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 else
return serverUrl;
and
if else
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