logo

Failing code | Part 2

from Code Cleanup #5

or check out part 1

Another problem when treating errors is that we sometimes forget to return an invalid return value. Let's check out the second rule regarding this:

2) Return a proper error

Alright, I get it, you don't want to use exceptions, they are way too cumbersome to use and can really hurt both performance of the programmer and its software. Therefore, there are only two other ways you can either have some sort of logger object that is passed around the application and used for error checking which, if you don't have one already, would require quite a bit of work to implement one. Or you could simply return an invalid return value for your method. Here is what I mean:

public int getCoordinatesCount(String routeString) { Route route = new Route(routeString); if (!route.isValid()) { System.err.println("Route is invalid!"); return 0; } List<Coordinates> coords = route.toCoords(); return coords.size(); }

For this use case, the return value is a simple count. Returning 0 would mean it didn't find anything in the given route which is returned in both cases where

  • the route is invalid
  • there are no coordinates found in route

There, we have a problem. 0 can be returned by both a valid or an invalid use case. The best way around it is to return a negative number. This assures that you can both check for errors and ignore errors with a simple if (count > 0). A simple modification goes a long way in this case:

public int getCoordinatesCount(String routeString) { Route route = new Route(routeString); if (!route.isValid()) { System.err.println("Route is invalid!"); return -1; } List<Coordinates> coords = route.toCoords(); return coords.size(); }

In some cases, null or undefined might be a better option, but for numeric variables this can be tougher.

We hope this helped so far. You can check out the last rule on the third part of this post. Or you can check out the shorter Code Cleanup #5 video we have posted not too long ago!