Monday, February 8, 2016

Magic Numbers and Hard Coded Values

My Auntie Pat Tern recently borrowed her friend's phone and noticed the recently called phone numbers didn't have names assigned, so she called everyone to remind them to enter contact names with their phone numbers.  I looked through some of the code in my org and decided to share her advice with my developers.  I found code that made use of Magic Numbers and hard-coded values, both of which make the code difficult to maintain.

Imagine Auntie Pat Tern's frustration when she wanted to find a particular number and couldn't because it wasn't listed under any of the names she expected to see.  And the contact list was empty.  She couldn't find the number she wanted and she couldn't tell what any number was for without a contact list.  In programming, the variable and constant declarations are like the contact list and allow us to give understandable names to numbers we use in the code. Numbers that appear without names and descriptions are known as "Magic Numbers" because they appear and seem to work by magic, such as the following example:

Imagine trying to maintain code like this, would you know where to change a value and how often that value may be repeated in the code for the same use?  Does 0.43 need to be changed to 0.435 every time it occurs in this class, or just in a single line of code.  These values should be named according to the business logic being automated and should be declared as constants for more readable and maintainable code.

Magic Numbers aren't the only hard-coded values I found in the code. Deep within the bowels of one utility class I found a user name hard-coded as the owner of all records generated by our integration with another database.

In the example above, you can see the hard-coded user name, but you can't see the fact that this was a real user, and happened to be someone who had left the company and so was deactivated.  A better approach for this would be to assign an owner that is an Apex-only user, a bot-user specific to this integration, rather than a real person, and define that user name as a constant.

Static variables, at the beginning of a class, provide an ideal location for declaring variables and constants associated with business logic.  At the beginning of the class, they can be near the class description, the comment that describes the business case being automated by the class, and make maintenance a breeze.

Naming values and putting them where others expect to find them will help you avoid problems like what happened with my Auntie Pat Tern.

No comments:

Post a Comment