title: Assert for null check
body: <p>It seems widely accepted that assert statements should be reserved for testing and disabled in production because errors should have been resolved by then, and enabling assertions affects performance. However surely the same could be said of null checks with if statements. Why is this code considered good for production</p>
  
  <pre><code>if(x != null) {
      x.setId(idx);
      if (y != null) {
          if (y.id == x.id) {
              x.doSth();
          }
      } else {
          //handle error
      }
  } else {
      //handle error
  }
  </code></pre>
  
  <p>but this code isn't? (Assuming assertions are enabled)</p>
  
  <pre><code>try {
      assert(x != null); 
      x.setId(idx);
      assert(y != null);
      if (y.id == x.id) {
          x.doSth();
      }
  } catch (AssertionError e) {
      //handle error
  }
  </code></pre>
  
  <p>I understand using an if statement when it's expected that a variable may not be initialized. However when it's for defensive coding, assert seems more elegant and readable.</p>
  
  <p>I also tested performance for each method with this: </p>
  
  <pre><code>public class AssertTest {
  
      static final int LOOPS = 10000000;
  
      public static void main(String[] args) {
  
              String testStr = "";
  
              long startNotEqualsTest = System.currentTimeMillis();
              for (int i = 0; i &lt; LOOPS; i++) {
                  if (testStr != null) {
                      testStr = System.currentTimeMillis() + "";
                  } else {
                      throw new RuntimeException("We're doomed");
                  }
              }
              long notEqualsTestDuration = System.currentTimeMillis() - startNotEqualsTest;
  
              testStr = "";
  
              long startAssertTest = System.currentTimeMillis();      
              for (int i = 0; i &lt; LOOPS; i++) {
                  try {
                      assert(testStr != null);
                      testStr = System.currentTimeMillis() + "";
                  } catch (AssertionError e) {
                      throw new RuntimeException("We're doomed");
                  }
              }
              long assertTestDuration = System.currentTimeMillis() - startAssertTest;
  
              System.out.println("Duration with if : " + notEqualsTestDuration + "ms");
              System.out.println("Duration with assert : " + assertTestDuration + "ms");  
      }
  }
  </code></pre>
  
  <p>Timing is about the same for both methods:</p>
  
  <pre><code>Duration with if : 1234ms
  Duration with assert : 1313ms
  </code></pre>
  
  <p>Disabling assertions makes very little difference:</p>
  
  <pre><code>Duration with if : 1391ms
  Duration with assert : 1375ms
  </code></pre>
  
  <p>Have I missed any compelling reasons why null checks with if conditions are preferable to assert?</p>