Common State
Many calculations share the same data elements even if the values are different. When you find such a calculation, communicate it by declaring fields in a class. For example, all calculations with cartesian points require an abscissa and ordinate. Since all cartesian points share the need for these values, they are most clearly expressed as fields:
int x;
int y
}
Contrast this technique with variable state, where objects of the same class potentially have different data elements. The advantage of common state is that it is clear from reading the code, either the fields themselves or the complete constructor, what data is necessary to have a well-formed object. Your reader will want to know what it takes to successfully invoke the functionality in your object. Common state communicates this clearly and precisely.
Common state in an object should all have the same scope and lifetime. Sometimes I am tempted to introduce a field that is only used by a subset of the methods in an object, or that is only valid while one method is being computed. In such cases I can invariably improve my code by finding somewhere else to store the data in question, perhaps a parameter or a helper object.
|
This work is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 Unported License |
