Literals

What are Literals and why would we use them?

Literals are pieces of data that are explicitly used. A literal string, for example, might be used for the label for a field. Literals are used when a static (as in unchanging) piece of data is needed. Say we need to calculate something based on days, not weeks. We could use a variable and give it a value of 7. We could also use a literal value of 7 in the calculation.

Use literals when the value is used once for strings. For numeric values (like 7) we might use the literal multiple times. The key with numerics is whether the value of 7 by itself is clear enough to convey its purpose. Using numerics without a clear source for the value is often referred to as “magic numbers”. This is a bad thing. If you use numerics in a manner that is unclear, at the very least, document each value so anyone reading it can determine each number’s purpose.

Some Examples

The following examples are to show good and bad uses of literals.

Good:


Fatal error: Uncaught Error: Class 'format' not found in /home/abentley/www/pages/pgm101/literal.html:38 Stack trace: #0 /home/abentley/_framework/library/framework.php(126): include() #1 /home/abentley/_framework/library/framework.php(60): FRAMEWORK::include_file() #2 /home/abentley/_framework/library/framework.php(1466): FRAMEWORK::respond() #3 /home/abentley/public_html/index.php(4): include_once('/home/abentley/...') #4 {main} thrown in /home/abentley/www/pages/pgm101/literal.html on line 38