Null Java data members versus methods
SoftwareI was working on my latest Java assignment for The Universities with my new Kyou Fujibayashi figure looking on (more on that later) when my seemingly natural instinct to create more work asserted itself. I could have fixed this problem with nulls and moved on, but I decided to create a little experiment.
When programming in object oriented languages I can't ever stand to access data members directly, I always have to use getter and setter methods regardless of how trivial. Problem is, in Java it's not simply a case of declaring data members as private and replacing any direct usage with a getter method later because we're dealing with fundamentally different structures (primitive and not).
For example, in this crappy application we're creating a new NullTest object and directly testing if its nullObject data member is null. Java cheerfully replies with our "We've got a null!
" on the console.
public class NullTest { Object grilledCheese; // <-- null public static void main(String[] args) { NullTest x = new NullTest(); if (x.grilledCheese == null) System.out.println("We've got a null!"); } }
Peachy. Now what if we try the same thing but we indirectly access the nullObject data member through a simple getter method. Same result?
public class NullTest { Object grilledCheese; // <-- null public static void main(String[] args) { NullTest x = new NullTest(); if (x.getNullObject().equals(null)) System.out.println("Getter method null!"); } public Object getNullObject() { return nullObject; } }
Nope! If we try running this, we get a big ol' NullPointerException. Our logic on the surface is pretty much the same, but when using objects returned from methods like this we'd have to use a try and catch block. Even better, because we've created a getter method to encapsulate the logic for that particular object anyway, we'd probably do some conditional checks in there instead. I would think.