The Problem
I have Data Transfer Objects with many accessors that return values of different types, for example Integer
, Double
, String
, etc.
The objects are initialized from parsing text, where a field that is an Integer
in the text being parsed, may also have a value of "INVALID." The user (developer in another module) of the class should know if the value they are getting is valid or not without having to catch an exception.
What I'm Considering
public class FooDto
{
private Integer a;
private Double b;
private Long c;
public FooDto(String rawText)
{
// Initialize members from rawText...
}
public Integer getA()
{
return a;
}
boolean isAValid()
{
boolean isValid = // determine validity
return isValid;
}
public Double getB()
{
return b;
}
public boolean isBValid()
{
boolean isValid = // determine validity
return isValid;
}
}
The Question
Is there a best practice, or library out there with IntegerWithValidityCheck
, DoubleWithValidityCheck
, etc. that I should be using? To be clear, this is different than just returning null. The return value could be null -- if the value doesn't exist in the text file, a valid value, or the specific case of "INVALID."
As I see it, you have two options:
The easiest is just to throw an exception for the exceptional case. I would imagine the case where the value isn't present would suit?
Create a new generic class that you return from each method. It can have an isInvalid()
method, which indicates whether the value was marked as "INVALID". If the user still calls getValue()
despite being told it was invalid, throw an exception.