![]() |
![]() |
|
|||||||
| infologic > developer > Conditional Code | |||||||
|
Often while developing source code, there are several alternative solutions to a problem. Until one of the solutions is chosen, the code may typically be written to contain all alternatives, but with a conditional (IF) statement determining which should be used. eg. private boolean SOLUTION_A = true;
...
if (SOLUTION_A) {
Once a specific solution is chosen the programmer has to decide what to do with the alternative solutions..
The correct approach will depend on many factors, including whether it is likely that the alternatives are to be used again, and any one of the above may be the correct approach. If approach c) is used, it is possible to ensure that the code application footprint is not compromised. The javac compiler detects and ignores statement blocks where the condition is known to be false at compile time. eg. if (true) {
becomes But a better, more descriptive way of acheiving this is to declare a field as final. The compiler knows the value will not change so can therefore include the true statement block, and ignore the false statement block. eg. ...
if (STATE) {
becomes Also -
if (AnotherClass.STATIC_FINAL_STATE) {
i = 1;
} else {
i = 2;
}
becomes Also -
private static final int MASK = 0x2;
private static final int FLAG0 = 0x1;
private static final int FLAG1 = 0x2;
if ( (MASK & FLAG1) != 0) {
becomes Other Possible UsesThe same approach can be used for including debug code, perhaps with a static final DEBUG flag declared in a common class. eg.
public class Debug {
public static final ON = false; // set true during development
}
public class AClass {
....
private void aMethod() {
....
....
if (Debug.ON) System.out.println("some debug");
....
....
}
}
|
|||||||
| |||||||