Use constants.

Avoid numbers and string literals.

Whenever a number appears in the code, it often represents a business concept. For example, maybe there’s a for loop that iterates 20 times, where 20 represents the number of rows on a page. That “20″ should not be there; what you really meant to code was “number of rows per page,” so make a constant, “NUMBER_OF_ROWS_PER_PAGE,” and use that instead.

In a large codebase, the chances are good that this “20″ concept appears more than once. And then one day, someone decides that you should only show 15 rows per page. So the developer changes the code in one place… and overlooks the “20″ in the other place. Next thing you know, you have an inconsistent codebase. Use constants to avoid this dumb mistake.

The same applies to string literals. When you see these in the code, it’s just like the problem with the “20″. Assign the string to a constant, and use it there.

For views where there is a lot of text, you should consider using an i18n solution. Not only does this keep all your consumer-facing text in one place, but it also makes it easy to support multiple languages.

That all said, some magic numbers are okay to stay as-is. You don’t need to replace “0″ with a constant for the start of the array. You don’t need to replace “100″ with a constant PENNIES_PER_DOLLAR or TOTAL_PERCENT. These are everyday concepts that aren’t going to change and become a problem later.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: