twitter

cognitive dissonance in java

It seems to me unintuitive to have things floating around = to null but able to call methods. for example: Show Plain Text
  1.  
  2. class Foo{
  3. static void doStuff(){ }
  4. }
  5. Foo foo = null;
  6. foo.doStuff(); //works
  7.  
The fact that though foo is null and is invoking a static method makes sense when carefully considered, but reduces the clarity of code when trying to understand large amounts of it at once.. this leads to increasing confusion as the system becomes more complex! This gets even more confusing when the relationship between the Type of null and the relationship of its static methods becomes more complex. for example: Show Plain Text
  1. public class Foo {
  2.    static int fubar = 42;
  3.    Foo getFoo() {
  4.      return null;
  5.    }
  6.    public static void main(String args[]) {
  7.    Foo foo = new Foo();
  8.    System.out.println(foo.getFoo().fubar);
  9.   }
  10. }
  11. // output : 42
c# on the other hand takes the approach of disallowing the calling of static methods on class instances. this intuitively seems easier to understand.
Update - Eclipse can be configured to trigger warnings for "indirect access to static members" under Java > Compiler > Errors/Warnings.