Saturday, April 14, 2012

Java should not aid inconsistencies

One of some leaky abstractions of Java: unboxing and comparison

class Main
{
  public static void main (String[] args) throws java.lang.Exception
  {
      Integer a = 7;
      Integer b = 7;
 
      Integer c = 200;
      Integer d = 200;
      
      // java should not aid comparing variable to literal, 
      // java language designer should make this a compilation error...
      System.out.println(c == 200); // true 
      System.out.println(d == 200); // true
 
      // ...because it gives the wrong impression that you could likewise 
      // do the same comparison on two variables:
      System.out.println(c == d); // false. what!? leaky abstraction that is!
      
 
      System.out.println(a == 7); // true
      System.out.println(b == 7); // true
 
      // this should be false. but it ain't, all numbers from -128 to 127 are cached(aka interning),
      // hence a and b points to the same memory location
      System.out.println(a == b); // true. what!? leaky abstraction that is!
 
           

      // this is way better. all the output are true
      System.out.println("\nBetter\n");

      System.out.println(a.equals(7));
      System.out.println(a.equals(b));
      System.out.println(c.equals(200)); // now we're talking
      System.out.println(c.equals(d));

       
      // and this comparison is infinitely better. 
      // when you want to compare if a is less than or equal to b, just change the '==' operator to '<='
    
      /*

      System.out.println(a.compareTo(7) == 0);
      System.out.println(a.compareTo(b) == 0);
      System.out.println(c.compareTo(200) == 0); // now we're talking
      System.out.println(c.compareTo(d) == 0);

      */
  }
}
Output:
true
true
false
true
true
true

Better

true
true
true
true
Leaky abstraction: http://www.joelonsoftware.com/articles/LeakyAbstractions.html

No comments:

Post a Comment