an acid test for method sanity

So, I just looked at a method call in an online tutorial and found this fairly simple code.

// Initialize the hasher without portable hashes (this is more secure)
$hasher = new PasswordHash(8, false);

What’s wrong with this? Not much maybe. Or maybe a lot. I have an acid test for method signatures: can I determine what the arguments are from the method name and parameter type(s)?

First things first, the first parameter ‘8’ may be given a name in production code, as might the ‘false’. That’s ok – I’m not interested in the quality of the calling code, just the signature of the method.

The crux of the problem – what is this method / constructor asking for? I read aloud the method with parameter types in place and try to determine the purpose of them. In this case I read out the following:

new Password Hash int boolean

What does this mean? No idea.

At first glance this seems like an ‘out there’ naive view of code, along the lines of ‘never use the String class’ but I feel this is a fundamental part of writing better code. Here I would prefer to create a ‘default hasher’ using a factory method maybe, assuming that I need an int and boolean to create a Password Hash. Now let me override the int and boolean with appropriate setters, e.g.

$hasher->setFluidOunce(8);
$hasher->setFrothy(false);

And there you have it, my acid test for method sanity.

Try with multiple catches


public void doStuff()
{

  try {
    doSomethingThatCouldBreak();
  } catch (InvocationTargetException ite) {
    logger.error("Caught error", ite);
    handleError(ite);
  } catch (IOException ioe) {
    logger.error("Caught error", ioe);
    handleError(ioe);
  } catch (SecurityException se) {
    logger.error("Caught error", se);
    handleError(se);
  }
}

Code like this really suggests that each of these exceptions will be a different scenario for your code. The list of potential exceptions, including RuntimeExceptions, is almost endless. If the way each exception is handled is the same don’t try to be cute picking and choosing your exceptions – catch Exception. If you catch it below the top-level of the application (which is where you normally handle exceptions that have bubbled up), you have typically got 2 things to do – log it, throw it wrapped in a RuntimeException or similar.

If you are writing more code for error handling than for functionality you are probably doing something wrong.