Many good programming practices boil down to preparing for change or expressing intent. It seems to me that novices emphasize the former, experts the latter.
One of the first things you learn in programming is to use symbolic constants rather than magic numbers. For example, if you have a maximum of 12 items in a shopping cart, define a constant like
MAX_ITEMS to be 12 and use that symbol rather than the number “12” throughout the code. That way if you have to increase the maximum to 25 some day, you can just make the change in one place. Symbolic constants prepare for change.
Sounds good, but then why define a constant for pi? It’s not going to change. But having a constant
PI in source code conveys the intention of the number.
There are 3,628,800 seconds in six weeks. Coincidentally, this number also equals 10!. But constants like
TEN_FACTORIAL clearly convey where the numbers come from. That’s why it’s sometimes worthwhile to give one thing two names. The symbol
SECONDS_PER_SIX_WEEKS looks like a conversion factor, while
TEN_FACTORIAL makes you think somewhere there are 10 things being arranged. Using the symbols in the opposite context would be clever, but not in a good way.
Expressing intent is easier to justify than preparing for change. If you argue that some chunk of code should be pulled out into its own function in case it needs to change, someone may argue “But that’ll never change.” If you argue that the same chuck of code should be pulled out and given a name to express what it’s trying to do, you’re likely to get less resistance.
If you focus on making your intentions clear, your code will be easier to maintain. If you focus on maintainability alone, it might backfire. You might get lots of unneeded code, inserted with the intent of making future maintenance easier, that makes maintenance harder.
More software development posts
For a daily dose of computer science and related topics, follow @CompSciFact on Twitter.