Rule 1: Don't depend on initialization
Most Java developers think there is no way to allocate an object without running a constructor. But this isn't true: there are several ways to allocate noninitialized objects.
The easy way to protect yourself against this problem is to write your classes so that before any object does anything, it verifies that it has been initialized. You can do this as follows:
- Make all variables private. If you want to allow outside code to access variables in an object, this should be done via get and set methods. (This keeps outside code from accessing noninitialized variables.) If you're following Rule 3, you'll make the get and set methods final.
- Add a new private boolean variable, initialized, to each object.
- Have each constructor set the initialized variable as its last action before returning.
- Have each nonconstructor method verify that initialized is true before doing anything. (Note that you may have to make exceptions to this rule for methods called by your constructors. If you do this, it's best to make the constructors call only private methods.)
- If your class has a static initializer, you will need to do the same thing at the class level. Specifically, for any class that has a static initializer, follow these steps:
- Make all static variables private. If you want to allow outside code to access static variables in the class, this should be done via static get and set methods. This keeps outside code from accessing noninitialized static variables. If you're following Rule 3, you'll make the get and set methods final.
- Add a new private static boolean variable, classInitialized, to the class.
- Have the static constructor set the initialized variable as its last action before returning.
No comments:
Post a Comment