type conversion - Nicely written check for numbers that can be null in java -


i have application need handle lot of numbers (integers or longs) comming external sources.

the numbers can null. in case null always need convert them 0.

the problem seems trivial, don't want write hundreds of times:

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

i don't 2 reasons:

  1. i don't write 3 lines of code such simple task, because need many times
  2. i don't to "mutate" somenumber (assign new value somenumber variable)

i tried other ways can seen here:

  public static void main(string[] args) {     integer zeroornull = new random().nextboolean() ? 0 : null;       // version1: nasty (i mentioned why)     if (zeroornull == null) {       zeroornull = 0;     }      // version2: seems simple task...     zeroornull = optional.ofnullable(zeroornull).orelseget(() -> 0);      // version3: creating util might considerable. there such predefined util ?     zeroornull = myutil.getvalueorzero(zeroornull); // returns value or )      system.out.println(zeroornull); // want 0 here in case of null     } 

what preffered , nice way such "test null/conversion 0" ? chance conversion implicitly?

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

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

place check close numbers source possible, avoid unnecessary duplications.


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -