cognitive dissonance in java
Jan 12, 2012
- under:
- java
It seems to me unintuitive to have things floating around = to null but able to call methods. for example:
Show Plain Text
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
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.
- class Foo{
- static void doStuff(){ }
- }
- Foo foo = null;
- foo.doStuff(); //works
- public class Foo {
- static int fubar = 42;
- Foo getFoo() {
- return null;
- }
- public static void main(String args[]) {
- Foo foo = new Foo();
- System.out.println(foo.getFoo().fubar);
- }
- }
- // output : 42
Update - Eclipse can be configured to trigger warnings for "indirect access to static members" under Java > Compiler > Errors/Warnings.