0

I have a class, which has lots of string fields. In the setter methods of all those field I have to do a check like this (As the data may be null):

public void setAddress1(String address1)
{
    this.address1 = Contract.checkNull(address1, "");
}

The class Contract is as follows:

public class Contract
{
   public static checkNull(String input, String output)
   {
      return (null == input) ? output : input;
   }
}

I have several of fields like 'address1' above. Is there any good method other than the above , to avoid the null? I have read avoiding != null, but is that applicable here ?

Community
  • 1
  • 1
kaushik
  • 1,820
  • 6
  • 27
  • 41
  • 3
    For one, several libraries (guava, apache-commons) have a Strings.defaultIfNull(str) type method. Otherwise, you can assume good input; perhaps annotating the parameter with @javax.annatotions.NotNull – Michael Deardeuff Mar 16 '13 at 06:35
  • 1
    Just to make the list complete I'd like to mention assertions. Using assertions is controversial though: http://programmers.stackexchange.com/questions/137158/is-it-better-to-use-assert-or-illegalargumentexception-for-required-method-param – ATrubka Mar 16 '13 at 06:40

3 Answers3

2

If you use java EE, you could use java validation API. NotNull is EE6 standard.

@NotNull
private String address1;
public void setAddress1(String address1)
{
    this.address1 = address1;
}

If you don't, you can still use something similar though non-standard.

Another good approach would be to use Null Object Pattern. In that, even nulls are represented as objects.

eis
  • 45,245
  • 11
  • 129
  • 177
  • I have mentioned about Null Object Pattern,but how can that implement with String? – kaushik Mar 16 '13 at 07:48
  • @kaushik having `static final String NULL_STRING = "null";` and using that as default. depending on the use case however - if you cannot modify the objects you get and they have nulls, then I don't think this is fully applicable – eis Mar 16 '13 at 08:41
  • however it think you could have an annotation that would replace nulls with this NULL_STRING. – eis Mar 16 '13 at 08:45
2

I recommend you to import the Apache String utility since you have lots of String notnull check. Because All the methods that this utility provides is null safe, it means that when the arguments is null, it doesn't throw NullPointException and can handle it very well. here is the API of it

OQJF
  • 1,330
  • 9
  • 12
1

You can use StringUtils.defaultString from Apache Commons Lang

public void setAddress1(String address1)
{
    this.address1 = StringUtils.defaultString(address1, "");
}
Iswanto San
  • 17,245
  • 11
  • 56
  • 77