We love errors!

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?

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.

Exclusive: Humans placed in suspended animation for the first time | New Scientist

Doctors have placed humans in suspended animation for the first time, as part of a trial in the US that aims to make it possible to fix traumatic injuries that would otherwise cause death.

via Exclusive: Humans placed in suspended animation for the first time | New Scientist

Interesting! This is, of course, one way to refine this technology to decrease bad side effects until it may be mature enough to even use it to go to Saturn…

Unless the side effects are worse than death, but it seems they’ve tested it on animals with good results…

Sherlock-Mode

When clearing up a mess*, rather than thinking you’re a cleaner having to clean up someone else’s shit, think that you are Sherlock Holmes trying to solve a mystery.

* In my case this is mostly about programming… it can also be problems I caused when writing (but then I’m only blaming someone else when it was a character’s fault… 🙂 )

%d bloggers like this: