Lets say have this immutable record type:
public class Record
{
public Record(int x, int y) {
Validator.ValidateX(x);
Validator.ValidateY(y);
X=x;
Y=y;
}
public final int X;
public final int Y;
public static class Validator {
public void ValidateX(int x) { if(x < 0) { throw new UnCheckedException; } }
public void ValidateY(int y) { if(y < 0) { throw new UnCheckedException; } }
}
}
Notice it throws an unchecked exception. The reason is because this is a object that is used quite often and it is inconvenient to have to deal with a checked exception.
However, if this object is in a class library where it may be used to validate user inputs (or some other external input). Now it's starting to sound like it should be a CHECKED exception, because the inputs are no longer up the to programmer.
Thoughts everyone? should i make checked or unchecked, or are there better design for this?
UPDATE:
my confusion is coming from this scenerio: normally Record would be used like this:
Record r = new Record(1,2);
OtherObj o = new OtherObj(r);
there it's up to the programmer, so unchecked exception is ok.
However when you get parameters for Record from a user you want to validate them right? so you might call
Record.ValidateX(inputX);
Record.ValidateY(inputY);
There it might throw a checked exception because inputs are no longer controlled?
Sorry, I normally wouldn't be too concerned with this (personally I think unchecked is fine). but this is actually a problem in a homework and I want to get it right lol.
UPDATE(2): I starting to think what I need is for ValidateX to throw a checked exception because it is typically what would be used if user input is involved. In that case we could ask the user for input again. However, for the Record constructor, it will throw checked exception because constructing a Record with invalid arguements is an API violation. The new code would look like this:
public class Record
{
public Record(int x, int y) {
try
{
Validator.ValidateX(x);
Validator.ValidateY(y);
}catch(CheckedException xcpt) { throw new UnCheckedException(xcpt.getMessage()); }
X=x;
Y=y;
}
public final int X;
public final int Y;
public static class Validator {
public void ValidateX(int x) throws CheckedException { if(x < 0) { throw new CheckedException; } }
public void ValidateY(int y) throws CheckedException { if(y < 0) { throw new CheckedException; } }
}
}
Now the programmer can validate the parameters before passing them to the Record class. If the does not then it's a API violation and an unchecked exception is thrown.
How does this sound?!