Experienced programmer: I am disappointed in this application… it doesn’t throw enough errors.
Inexperienced programmer: Huh?!?!
Errors are your friend because they tell you that something went wrong, and you get a list of potential places where it went wrong with line numbers in the code and everything (if you’re in debug mode, and using a somewhat mature framework).
In a contrary, applications that do their damndest to avoid errors usually end up doing nothing, or the wrong thing, without complaint, and your debugging effort is more akin to that of a therapist than a programmer.
Here are a few things to consider.
Don’t swallow exceptions
try { //...do something that may throw an error } catch (Throwable t) {}
If you don’t know what to do with the error, don’t catch it. If you need to do something, catch the error but throw another if the error is still a problem.
Stopping errors should propagate all the way to the user interface where they can be packaged nicely in a dialog or error page or some other device that prompts the user to provide other input, change the application configuration or call an admin.
If the error prevents the application from doing its job, the error prevents the application from doing its job. Period!
Of course, the best way to deal with user input is to implement data validation to prevent bad data from ever get past the UI of the application (which of course isn’t possible to do in all cases… hence the rest of this article.)
If a resource is involved, look into the try-with-resource-construct in Java or the using-construct in .Net. They will close a resource if there was an error or not.
Don’t throw exceptions with no or whimsical messages
Never throw errors without a message. Or with an ambiguous message:
if (value > max) throw new IllegalStateException("Error!");
Do you hate the above code? Good, it’s the classic Mac OS “An error of type 1 has occurred”-error message all over again. (And I’ve actually seen something like it in a mature paid-for product).
Return a meaningful error message. If you can, also add information about why there was an error:
if (ds.Tables[0].Rows.Count == 0) { throw new Exception( "Unable to locate super user (user with ID=1)"); }
Imagine you’re the one getting the error message, and you’ll probably know what to do and that you need to do it.
Don’t use return values instead of exceptions
public int doSomething() { if (unable to do what I should) return -1; .. }
If you run into an error condition, throw exceptions instead of returning values.
A calling method may mistake that -1
for a valid response. It will not mistake an exception in the same way!
There may be a case for returning null
in some cases, for instance when there are no data.
Don’t fear null
Null, by the way, is another underutilized feature of programming.
In Java 8 there’s the Optional-class that can be used in cases where the value may or may not exist (e.g. a search).
Before Java 8 you have different options.
For a search, you could return an empty list.
However, when dealing with values that may, or may not, be set, null is the only way to go. (Pre- and post-Java 8).
Consider the following (slightly edited real-life) example:
public List<RowDto> GetItems( List<ColumnDto> columns, string userName, string searchTerm, List<int> filters, string sortColumn, bool sortDescending, int numberOfRows) { .. }
Now consider that the actual implementation of the view that displays items can have default sort ascending or descending.
How do you know when the framework asks for default sort or when the user has decided they want a specific sort (by clicking the headline of the column to sort)?
You don’t.
The sortDescending
variable should have been nullable (bool? sortDescending
in .Net/C# parlance).
In that case, it would have been possible to check for a null value (signaling default sort) and determine if the sort should be ascending or descending depending on the specification of the view.
Here’s another example where a value may be set or not, but the whole null handling has been hidden from the outside world (not that different from Optional, but with the ability to set the value as well, and several values in the same object…):
public class MyClass { public int getValue() { if (value == null) throw new IllegalStateException(...); return value; } public void setValue(int value) { this.value = value; } public void unsetValue() { value = null; } public boolean isValueSet() { return value != null; } public String getValue2() ... public Object getValue3() ... private Integer value; private String value2; private Object value3; }
Catch error conditions early and throw exceptions (but do it right…)
Another tip is to catch errors early and throw exceptions. E.g. in Java 8, use the Objects.requireNonNull()
-function.
However, always make sure your methods first verify the in-data and only then start changing the state of the object. Otherwise, if that object survives your mishandling, it will likely cause ripple effects throughout the application.
Consider the following:
public void myMethod(Object o1, String s1) { if (o1 == null) throw new NullPointerException(); someOtherMethod(o1); .. + other work on o1 if (s1 == null) throw new NullPointerException(); .. do some work with s1 }
What happens to the state of this object if o1
is non-null and s1
is null?
Build a better system
One system I’m building generates a static site, but it takes a long time to do this, so I’ve decided to make sure my code is as efficient as it can possibly be:
public Writer writer(File file) throws FileNotFoundException { Objects.requireNonNull(file, "Argument file is null"); if (renderedFileList.contains(file)) { throw new IllegalStateException( "Trying to write the same file twice: " + file); } renderedFileList.add(file); ... }
This way I can always rest assured my programming never creates the same file more than once, and if I were to get this error, rather than calling it an unnecessary check and remove it, I’d go in and remove the second rendering… unless of course, I’m overwriting files…
After all, that site takes several minutes to render, so I’d rather only render it once!
As I’ve gained experience in programming I’ve come to change my opinion about errors and program crashes from “Oh! F*ck!” when I got them, to “hmmm, what’s up?” when I keep pounding in code without getting them.