Menu
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) {
... } else { ... }

Once a specific solution is chosen the programmer has to decide what to do with the alternative solutions..

a) Delete source lines Neater source, removes clutter. But difficult to change back.
b) Comment out source lines Alternative code can relatively easily be re-instated. May help support engineers/future developers to understand the options available/decisions taken. But code may appear cluttered.
c) Leave all solutions in code Easier to reinstate. But unused code is included which adds to the application footprint (size). This is more of an issue for MIDlet applications where the application footprint needs to be small.

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) {
i = 1; } else { i = 2; }

becomes
i = 1;

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.
private static final boolean STATE = true; // STATE is final so compiler knows it will always be true

...
if (STATE) {
i = 1; } else { i = 2; }

becomes
i = 1;

Also -
if (AnotherClass.STATIC_FINAL_STATE) {
    i = 1; 
} else { 
    i = 2; 
} 

becomes
i = 1;

Also -
private static final int MASK = 0x2;
private static final int FLAG0 = 0x1;
private static final int FLAG1 = 0x2;

if ( (MASK & FLAG1) != 0) {
i = 1; } else { i = 2; }

becomes
i = 1;

Other Possible Uses

The 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");
        ....
        ....
    }

}