10.5. Persistence

 < Free Open Study > 

"Persistence" is another word for the life span of a piece of data. Persistence takes several forms. Some variables persist

  • for the life of a particular block of code or routine. Variables declared inside a for loop in C++ or Java are examples of this kind of persistence.

  • as long as you allow them to. In Java, variables created with new persist until they are garbage collected. In C++, variables created with new persist until you delete them.

  • for the life of a program. Global variables in most languages fit this description, as do static variables in C++ and Java.

  • forever. These variables might include values that you store in a database between executions of a program. For example, if you have an interactive program in which users can customize the color of the screen, you can store their colors in a file and then read them back each time the program is loaded.

The main problem with persistence arises when you assume that a variable has a longer persistence than it really does. The variable is like that jug of milk in your refrigerator. It's supposed to last a week. Sometimes it lasts a month, and sometimes it turns sour after five days. A variable can be just as unpredictable. If you try to use the value of a variable after its normal life span is over, will it have retained its value? Sometimes the value in the variable is sour, and you know that you've got an error. Other times, the computer leaves the old value in the variable, letting you imagine that you have used it correctly.

Here are a few steps you can take to avoid this kind of problem:

  • Use debug code or assertions in your program to check critical variables for reasonable values. If the values aren't reasonable, display a warning that tells you to look for improper initialization.

    Cross-Reference

    Debug code is easy to include in access routines and is discussed more in "Advantages of Access Routines" in Section 13.3.


  • Set variables to "unreasonable values" when you're through with them. For example, you could set a pointer to null after you delete it.

  • Write code that assumes data isn't persistent. For example, if a variable has a certain value when you exit a routine, don't assume it has the same value the next time you enter the routine. This doesn't apply if you're using language-specific features that guarantee the value will remain the same, such as static in C++ and Java.

  • Develop the habit of declaring and initializing all data right before it's used. If you see data that's used without a nearby initialization, be suspicious!

 < Free Open Study > 


Code Complete
Code Complete: A Practical Handbook of Software Construction, Second Edition
ISBN: 0735619670
EAN: 2147483647
Year: 2003
Pages: 334

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net