Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
The material for this article (avoiding special data values, using constants, minimizing coupling) and the next article (maximizing cohesion) may be familiar to many readers, as the material is based on general design principles that are quite independent of the Java programming language. Nevertheless, because I have encountered so much code over the years that doesn't take advantage of these principles, I think they deserve to be restated from time to time. In addition, in this article I attempt to show how these general principles apply to the Java language in particular.
In designing fields, the main rule of thumb is to avoid using one variable to represent multiple attributes of a class. You can violate this rule by denoting special values within a variable, each with its own special meaning.
As used here, an attribute is a distinguishing characteristic of an object or class. Two attributes of a CoffeeCup object, for example, could be:
To take a closer look at this rule, imagine you are designing a CoffeeCup class for the virtual café described in last month's Design Techniques column. Assume you want to model whether or not a coffee cup in your virtual café has been washed and is ready for use by
the next customer. With this information on hand, you can ensure that you don't reuse a coffee cup before it has been washed.
If you decide you only care whether or not a cup has been washed if it is empty, you could use a special value of the innerCoffee field, which normally is used to keep track of the amount of coffee in the cup, to represent an unwashed cup. If 473 milliliters
(16 fluid ounces) is the maximum amount of coffee in your largest cup, then the maximum value of innerCoffee normally would be 473. Thus, you could use an innerCoffee value of, say, 500 (a special value) to indicate an empty cup that is unwashed:
// In source packet in file fields/ex1/CoffeeCup.java
class CoffeeCup {
private int innerCoffee;
public boolean isReadyForNextUse() {
// If coffee cup isn't washed, then it's
// not ready for next use
if (innerCoffee == 500) {
return false;
}
return true;
}
public void setCustomerDone() {
innerCoffee = 500;
//...
}
public void wash() {
innerCoffee = 0;
//...
}
// ...
}
This code will give CoffeeCup objects the desired behavior. The trouble with this approach is that special values aren't readily understood, and they make
code harder to change. Even if you describe special values in a comment, it may take other programmers longer to understand
what your code is doing. Moreover, they may never understand your code. They may use your class incorrectly or change it such
that they introduce a bug.