CodeVault - Failing code | Part 1
Logo picture

Code Cleanup - Failing Code | Part 1

from Code Cleanup #5

Let's start simple. You have a method that, sometimes, when called with certain arguments or at certain times it might fail. How do we tell that to the user? What about to the programmer using that method?

The answer is quite simple: the programmer will see the method failing because of an exception being thrown or return some sort of error message and the user should see this through error propagation done by the programmer calling the method or through an automatic way.

For this to happen we have to establish a few rules when creating our methods:

1) Do not let your methods fail silently

This is very prevalent when assuming a certain state for your data and forgetting to check if the data doesn't have that certain state. Let's look at an example:

public void repair(RepairType type) { CarRepair carRepair = car.doRepair(type); if (carRepair != null) { System.out.println("The car is still " + carRepair.getStatus()); car.setUnavailableFor(carRepair.getDuration(), Unit.HOURS); } }

What happens when we call this code? We have no return value, no exception being thrown, no nothing. A simple way of preventing this is to treat validation errors first and at the end of the method have the actual code that is normally executed.

We have discussed about this method in our "Invert your ifs" post but not without an actual error treatment. To complement our convention we should also have the code that represents what the method actually does at the end of the method and preferably starting with no indention. Also, returning some sort of error is a must. Here's is the improved code snippet:

public boolean repair(RepairType type) { CarRepair carRepair = car.doRepair(type); if (carRepair == null) { System.err.println("The repairman for type " + type.toString() + " in unavailable"); return false; } System.out.println("The car is still " + carRepair.getStatus()); car.setUnavailableFor(carRepair.getDuration(), Unit.HOURS); return true; }

As you can see, we are now treating the error and also know when this might have failed. Some more improvements, depending on your case are available:

We hope this helped so far. For the other rules you can check out the second part of this post. Or you can check out the shorter Code Cleanup #5 video we have posted not too long ago!

Get notified when a blog post is released

+ Free Clean Coding Guide