Conditional compile

The conditional compilation practice is used to optionally remove chunks of code from the compiled version of a class. It uses the fact that compilers will ignore any unreachable branches of code.

To implement conditional compilation,

This practice is used mostly for implementing debugging statements, logging statements, and for assertions. With the advent of assert and the Logging API in JDK 1.4, the utility of conditional compilation is probably reduced.

Example


public final class Debug {
  //set to false to allow compiler to identify and eliminate
  //unreachable code
  public static final boolean ON = true;
} 


This class uses Debug to implement conditional compilation :

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

/**
* Uses conditional compilation to optionally print debugging statements.
*/
public final class GenericServlet extends HttpServlet {

  public void init(ServletConfig aConfig) throws ServletException {
    super.init(aConfig);

    //print out a message, but only if Debug.ON evaluates to true
    //if Debug.ON evaluates to false, this entire block of code will be
    //passed over by the compiler, and will not be present in output .class file
    if (Debug.ON) {
      System.out.println("**** INIT OF My Controller *****");
    }
  }

  public void doGet(
    HttpServletRequest aRequest,
    HttpServletResponse aResponse
  ) throws ServletException, IOException {
    if (Debug.ON) {
      System.out.println("Processing doGet");
    }
    doHttpRequest(aRequest, aResponse);
  }

  public void doPost(
    HttpServletRequest aRequest,
    HttpServletResponse aResponse
  ) throws ServletException, IOException {
    if (Debug.ON) {
      System.out.println("Processing doPost");
    }
    doHttpRequest(aRequest, aResponse);
  }

  // PRIVATE //
  private void doHttpRequest(
    HttpServletRequest aRequest,
    HttpServletResponse aResponse
  ) throws ServletException, IOException {
     //empty
  }
} 



See Also :
Assertions in general
Logging messages
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -