Friday, April 5, 2013

Diagnostics You Can Disable

Maybe some of you - like me - come from languages where diagnostic functions can be removed from the code with the flip of a preprocessor flag. I miss that. Diagnostics are great for debugging and catching problems during development, but at release time, you'll want them gone to speed up your code.

The following is a global Apex class that allows you to do just that. Kinda. Actually, it's not nearly as good as removing the code since we still need to execute a few lines, but we're choosing quality over performance here, right? Sprinkle your code with SF.debug(...) and SF.assert(...) statements, then turn them all off simply by setting debuggingValue = false. Move debuggingValue to a custom setting to allow it to be toggled even in a production environment.

global class SF {
  //--------------------------------------------------------------------------
  // Diagnostics
  private static transient Boolean debuggingValue = true;
  public static Boolean debugging { get { return debuggingValue; }}
 
  public static void debug(Object message) {
    debug(LoggingLevel.DEBUG, message);
  }
  private static void debug(LoggingLevel level, Object message) {
    if (debugging) {
      System.debug(level, message);
    }
  }
 
  public static void assert(Boolean condition) {
    assert(condition, null);
  }
  public static void assert(Boolean condition, Object message) {
    if (debugging && !condition) {
      throw new SF.AssertionException(String.valueOf(message));
    }
  }
  public static void assertEquals(Object v1, Object v2) {
    assertEquals(v1, v2, null);
  }
  public static void assertEquals(Object v1, Object v2, Object message) {
    if (debugging && (v1 != v2)) {
      throw new SF.AssertionException(String.valueOf(message));
    }
  }
  public static void assertNotEquals(Object v1, Object v2) {
    assertNotEquals(v1, v2, null);
  }
  public static void assertNotEquals(Object v1, Object v2, Object message) {
    if (debugging && (v1 == v2)) {
      throw new SF.AssertionException(String.valueOf(message));
    }
  }
}

No comments:

Post a Comment