Chapter 9.  Protection

Prev don't be afraid of buying books Next

Chapter 9. Protection

A refactoring that improves the protection of existing code must do so in a way that doesn't alter the behavior of the existing code. All three refactorings in this section do just that. Your motivation for applying them may be to improve protection or it may be a standard refactoring motivation, such as to reduce duplication or to simplify or clarify code.

Replace Type Code with Class (286) helps protect a field from assignments to incorrect or unsafe values. This is particularly important when a field controls what behavior gets executed at runtime because an incorrect assignment could put an object into an invalid state. Replace Type Code with Class (286) uses a class rather than an enum to constrain what values may be assigned to a field. Does an enum provide a better way to implement this refactoring or even render this refactoring out of date? It does not. The main difference between a class and an enum is that you can add behavior to a class. This is important because the class produced during Replace Type Code with Class (286) may need to be extended with behavior as you apply a sequence of refactorings. This is exactly what occurs during the refactoring Replace State-Altering Conditionals with State (166).

Limit Instantiation with Singleton (296) is useful when you want to control how many instances of a class can be instantiated. Typical motivations for applying this refactoring are to reduce memory usage or improve performance. A poor motivation for refactoring to a Singleton [DP] is to give a piece of code access to hard-to-reach information (see Inline Singleton, 114, for a discussion of this). In general, it's best to apply Limit Instantiation with Singleton (296) only when a profiler informs you that doing so is worthwhile.

Introduce Null Object (301) is a refactoring that helps transform how code is protected from null values. If you have a lot of the same conditional logic that checks for the same null value, you can likely simplify and condense the code by refactoring it to use a Null Object [Woolf].


Refactoring to Patterns (The Addison-Wesley Signature Series)
Refactoring to Patterns
ISBN: 0321213351
EAN: 2147483647
Year: 2003
Pages: 103

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: