Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing value in Java

Tags:

java

What is the statement that can be used in Java to represent a missing value of a variable. for instance I want to write a code:

if (a>=23)
 income = pay_rate;
else 
 income is missing;
like image 407
SOS Avatar asked May 30 '12 04:05

SOS


2 Answers

There is a lot of bad advice in this thread. First let me address why you should not be going for some of the suggested approaches.

1. Using wrapper types and null

Integer income = null;
if (a >= 23) {
  income = payRate; 
}

Java has auto-unboxing. What if you somewhere accidentally use income in a place where Java had to auto-unbox it? The compiler cannot catch this error and your code will blow up at runtime.

Secondly, the "nullability" of income is not part of income's type. As a result, it's up to the programmer to be careful about checking it for null every time it is used. If he forgets to perform this check, compiler will not complain, but you will get NullPointerExceptions at runtime.

2. Using sentinel values to denote exceptional conditions

int income = Integer.MAX_VALUE;
if (a >= 23) {
  income = payRate;
}

This approach shares the second drawback of null approach. Even worse, in this case, instead of throwing an exception, computation will continue even in erroneous conditions, since Integer.MAX_VALUE is a valid int, leading to possible disastrous outcomes.


So how should you deal with this?

Use a data type that:

  • has "nullability" expressed in its type.
  • does not involve conditional checks such as in above two approaches.
  • ensures at compile time that the data is not being accessed in illegal state.

Maybe (also known as Option) fits the bill. (@Bahribayli already suggested this. I am expanding on it.) See the data definition here.

And this how you would use it in your case:

Maybe<Integer> income = Nothing.value();
if (a >= 23) {
  income = Just.of(payRate);
}

There is a library named Functional Java that provides this abstraction. If you have any further questions regarding the use of this data type, I will be happy to answer them.

like image 156
missingfaktor Avatar answered Oct 12 '22 13:10

missingfaktor


You are looking for a value, not for a statement, and that value is null. You cannot assign null to variables of primitive data types, such as int and double, but you can use it with their boxed counterparts -- Integer, Double, et cetera.

When you do that, you should be careful to check your values for null before accessing them. Otherwise, an innocent-looking if (pay_rate > 100) may throw a null reference exception.

like image 30
Sergey Kalinichenko Avatar answered Oct 12 '22 15:10

Sergey Kalinichenko