Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve differentiation between undef and null values for java data types

Tags:

java

What is the common approach followed in applications if we have to differentiate between 'undefined' value and 'null' value for properties in a class?

For example, let's say we have a class A

public class A {
 Integer int1;
 Boolean bool1;
 Double doub1;
 String str1;
}

In the code, we would like to differentiate if each property of A is either set or not set (null is a VALID value to set).

One approach is to have custom data types extending from java datatypes. Other approach is to assign some arbitrarily unreachable values to each of the data types and treat those values as undef.

Are there any other better approaches?

like image 447
Ramesh Avatar asked Sep 05 '25 03:09

Ramesh


1 Answers

I would use generics to create a wrapper which includes a 'set' flag.

public class Settable<T> {

  private boolean isSet = false;
  private T value;

  public Settable() {}

  public boolean isSet() {return isSet;}
  public T value() { return value;}
  public void set(T t) { value = t; isSet = true;}
}

...then declare your class with e.g.

public class A {
  //...
  Settable<Integer> int1;
  //...
}
like image 58
sje397 Avatar answered Sep 08 '25 01:09

sje397