0

We are using Java (1.7) for our application and I have got the below Train class:

public class Train {

    private String number;

    private String origin;

    private String destination;

    public Train(String number, String origin, String destination) {
        //set the fields
    }

    //other fields

    private int latenessAtOriginInMinutes;//optional Field

    //getters and setters
}

Assume that the field latenessAtOriginInMinutes is optional, when I instantiate the object Train train = new Train(1234, "A", "B"), the latenessAtOriginInMinutes will get the value 0 (which is the default for int types) for the object referenced by train, so then how can I differentiate that the 'lateness' is really zero or is it the default value (of primitive int) set by the JVM?

One way to solve this problem is simply setting latenessAtOriginInMinutes=99999 (some high default value) initially through the constructor, but each time when I retrieve the value from the database, I need to check that the value is latenessAtOriginInMinutes != 99999 to find the real lateness value, which I did not like.

The other way is to use OptionalInt in Java8, but we are currently using Java 1.7.

The other alternative is declaring latenessAtOriginInMinutes type as Integer, but I am not sure if this is the best option.

So, my question is, what is the best way to handle the optional fields like latenessAtOriginInMinutes?

Vasu
  • 21,832
  • 11
  • 51
  • 67
  • 1
    Use an Integer, leave it to null by default. – JB Nizet Mar 04 '17 at 10:54
  • You seem so determined to use a primitive? Why not use an object wrapper which can be `null`? – qqilihq Mar 04 '17 at 10:55
  • I thought about that i.e., wrapper classes (will add to the above), but I am thinking if there is any other better option? – Vasu Mar 04 '17 at 10:56
  • Use Guava's Optional? Use a better marker value than 9999, like -1? Define a Lateness type that tells if lateness has been set or not. It's up to you. – JB Nizet Mar 04 '17 at 10:57
  • Unfortunately, we can't take -1 as -1 can be a value for lateness (if the train departs early), so taken higher positive value. – Vasu Mar 04 '17 at 10:59
  • @PVS in that case, try `Integer.MAX_VALUE` – Peter Lawrey Mar 04 '17 at 12:30

0 Answers0