Lately I've been paranoid about some of my java classes and I've been inserting exceptions everywhere where I can to make sure I'm not setting values to null or getting values if they aren't initialized properly. At first, this seemed like a good idea following the standard pattern of validation:
public method doSomething(arg1)
{
if(!isValidArg1(arg1))
{
throw new IllegalArgumentException;
}
...
}
But this is getting to the point where each and every one of my getters/setters looks like this:
public String getLogicalName()
{
if (logicalName == null)
{
throw new UninitializedAttributeException("attribute: logical name.");
}
return logicalName;
}
public void setLogicalName(String logicalName)
{
if (StringUtils.isBlank(logicalName))
{
throw new IllegalArgumentException("attribute: logical name, illegal value: null, empty or whitespace.");
}
this.logicalName = logicalName;
}
Apart from losing too much time on coding these trivial methods, I feel like i'm overdesigning. Sure, debugging becomes more straigthforward, but its not like a normal nullpointerexpection doesn't show you what the problem is.
The main reason why I throw all these exceptions is because I want to present the end user on the front end with a clear message of what went wrong. I'm disappointed by some programs who just catch(Exception e)
wrapped around all their code, and if something goes wrong somewhere all the user sees is "something went wrong somewhere but I can't tell you what and where.". However, most of the time, the user cannot do anything about these exceptions because it's a development issue (although it is nice the user can tell the developer exactly what went wrong...). So is this overdesigned?
I'm in doubt about this. How do you other developers cope with this? What are some cases where explicitly checking the input/output values of a method is good practice, and what are cases where its redundant and clutters up the source code? Can a line be drawn?