I have done quite a bit of research on best ways to deal with null objects. The best I came across so far is using the Ternary Operator.
Str开发者_Python百科ing x = object.getString1!=null?object.getString1:"";
However I am not really satisfied with this since it still means constantly checking for null. The other thing I have read about was not having getter methods that return null but returning a "Null Object" instance. However I do not see how I could get this to work for Integers/BigDecimal/etc... since they by default hold a value.
I am not 100% keen on the idea of implementing NullObjects either. Has anyone else got a better idea of how to go about handling null's?
If your approach works well for you, why not refactor it to a static method and use all the time?
Google Guava has done something similar for strings. If you take a look under the hood of Strings class, you can see the nullToEmpty
method which is implemented like this:
public static String nullToEmpty(@Nullable String string) {
return (string == null) ? "" : string;
}
Don't concern yourself with the @Nullable
annotation.
But from your code, I suspect there are bigger problems lurking around. Null Integers and BigDecimal are a sign that something, somewhere isn't really right, and you might want to check the relevent parts. Having these objects set somewhere to null could be an indicator that you should be throwing an exception, but that decision is up to you, of course.
Assuming you are using C#, you could use the operator ??
:
String x = object.getString1 ?? "";
which is, IMHO, more readable.
As for your question, I can't see where's the point in using Null Object pattern for value type, as you already noted they can't hold a null value unless they are declared as Nullable so you will always have a valid value (valid in the language domain but maybe not valid in the application domain). So, this is a whole different question.
What you have to do with a null pointer really depends on the context, maybe a Null Object is suitable, but if it's not feasibile you should throw an exception or maybe use some default...
精彩评论