7

I have an application where I need to handle a lot of numbers (Integers or Longs) comming from external sources.

The numbers can be null. In case they are null I always need to convert them to 0.

The problem seems trivial, but I don't want to write hundreds of times:

if (someNumber == null) {
    someNumber = 0;
} 

I don't like it for two reasons:

  1. I don't like to write three lines of code for such simple task, especially because I need to do it many times
  2. I don't like to to "mutate" someNumber (assign new value to someNumber variable)

I tried some other ways which can be seen here:

  public static void main(String[] args) {
    Integer zeroOrNull = new Random().nextBoolean() ? 0 : null;


    // version1: this is nasty (I already mentioned why)
    if (zeroOrNull == null) {
      zeroOrNull = 0;
    }

    // version2: this seems to much for so simple task...
    zeroOrNull = Optional.ofNullable(zeroOrNull).orElseGet(() -> 0);

    // version3: creating an util might be considerable. Is there already such predefined util ?
    zeroOrNull = MyUtil.getValueOrZero(zeroOrNull); // returns value or )

    System.out.println(zeroOrNull); // I want 0 here in case of null


  }

What is the preffered and nice way to do such "test for null/conversion to 0" ? Any chance to do this conversion implicitly?

14
  • 2
    When you get the numbers from the external source, you must have some code that reads them into Integers. That code must distingish between nulls and not nulls anyway (for example, if you use Integer.parseInt(string), it will only work for non-empty Strings), so you can convert the nulls to 0 in that code.
    – Eran
    Jun 19, 2015 at 12:22
  • 2
    It seems, you already mentioned all alternatives. All of them look ok, but their necessity is obviously a symptom for a much heavier design problem. If you design a method that simply cannot accept a null value, then just do not allow it. Change the calling code at first to not send in null. If you still must distinguish between present and absent, then use java.util.Optional, but as a method parameter (not inside the method for its implementation). Jun 19, 2015 at 12:24
  • 2
    There is nothing wrong with doing if (someNumber == null) { someNumber = 0; } that is exactly what you should do.
    – brso05
    Jun 19, 2015 at 12:27
  • @Eran: This would be an option. The problem is that I would need to do such conversion in every place where I get this numbers. Maybe this is a solution, but I would prefer to test it anyway to avoid NPE in case someone forgot to do "conversion" in one of the "source places".
    – walkeros
    Jun 19, 2015 at 12:29
  • 2
    Using Google Guava you can write Integer i = MoreObjects.firstNonNull( possibleNull, 0);
    – biziclop
    Jun 19, 2015 at 12:31

5 Answers 5

4

Use i = (i==null)?0:i;

  • one line check
  • no method call
  • plain and simple
  • no additional dependency (unlike some other proposed solutions)

Place this check as close to your numbers source as possible, to avoid unnecessary duplications.

2

By creating overloaded versions of Null Checker

public static void main(String args[]) {

    Integer intObj = null;
    System.out.println("intObj : " + checkNull(intObj));

    intObj = 1122222;
    System.out.println("intObj : " + checkNull(intObj));

    Long longObj = null;
    System.out.println("longObj : " + checkNull(longObj));

    longObj = 666555556L;
    System.out.println("longObj : " + checkNull(longObj));

    System.out.println("*********With default value***********");

    intObj = null;
    System.out.println("intObj : " + checkNull(intObj, 1));

    intObj = 1122222;
    System.out.println("intObj : " + checkNull(intObj, 1));

    longObj = null;
    System.out.println("longObj : " + checkNull(longObj, 0L));

    longObj = 666555556L;
    System.out.println("longObj : " + checkNull(longObj, 0L));
}

static Integer checkNull(Integer obj) {
    if (obj == null)
        return 0;
    return obj;
}

static Long checkNull(Long obj) {
    if (obj == null)
        return 0L;
    return obj;
}

static Integer checkNull(Integer obj, int i) {
    if (obj == null)
        return i;
    return obj;
}

static Long checkNull(Long obj, long l) {
    if (obj == null)
        return l;
    return obj;
}
1

A simple solution would be to write a utility method like below:

public static Integer checkNullNumber(Integer i){
if(i == null)
   return 0;
return i;
}

Now you can use this method wherever you want like:

zeroOrNull = checkNullNumber(zeroOrNull);
1
  • I already mentioned it as "version3". There problem with your static method is that it only accepts Integers and I can have Longs. This can be fixes with Number type. This is and option, but if I would go for it I would prefer some external lib.
    – walkeros
    Jun 19, 2015 at 12:40
1

I don't like to write three lines of code for such simple task, especially because I need to do it many times

if (zeroOrNull == null) zeroOrNull = 0;

I don't like to to "mutate" someNumber (assign new value to someNumber variable)

there is no way to change the null-value into a "0" without constructing a new Integer object that holds this "0" and this single line of code does just that

1
  • The solution by plastique performs an assignment to "i" in the "else" case and therefor is less efficient than a simple "if" check. Jun 19, 2015 at 12:48
-1

Use java8 java.util.Optional class is very efficient, but don't use explicit null values, use empty Optional

This is my original answer, if "efficient" was intended only by "performance" I've wronged word, sorry.

The mean is that all coding process is better, develop and execution are more safe.

http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html

6
  • The values comes from external source, do you want me to wrap them into Optional? I already gave an example of Optional.ofNullable(zeroOrNull).orElseGet(() -> 0) Is that what you mean? And why do you say it is very efficient? Can you prove it?
    – walkeros
    Jun 19, 2015 at 12:24
  • 1) OP already mentioned the alternative Optional. Why do you suggest it? What is the benefit? 2) What brought you to the statement that it "is very efficient"? Where is this efficiency? Any sources? Sorry, this is not a good answer, so I had to downvote. Jun 19, 2015 at 12:27
  • my answer is based on your code, you set zeroOrNull to null then use Optional utils to compare values, is a nonsense. If you have different scenario post real code. The efficenty is not my opinion, but from Oracle articles that expose the introduction of the new API
    – fantarama
    Jun 19, 2015 at 12:42
  • @Seelenvirtuose he ask which solution is better, and I've answered, he didn't ask for a new one. Beneficts are exposed by Oracle articles, I can copy and paste the text here
    – fantarama
    Jun 19, 2015 at 12:50
  • @fantarama: If you say something is efficient you need to post a link to article (or another proof) together with your answer, otherwise this answer is not good.
    – walkeros
    Jun 19, 2015 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.