In my mind nothing says “junior developer” like an early return. Perhaps that’s unfair but I expect people to think about their work, not just copy what they see others doing, and it doesn’t take a lot of introspection to reject this kind of thinking.

The ER is part of a larger kind of faulty thinking. Here’s some C style pseudocode:

Thing thing = createThing();if (thing == NULL)
{
logger.error("no thing");
return;
}
Hoob hoob = createHoob();if (hoob == NULL)
{
logger.error("no hoob");
releaseThing(thing);
return;
}
Glork glork = createGlork();if (glork == NULL)
{
logger.error("no glork");
relesaeHoob(hoob);
releaseThing(thing);
return;
}
doWhatWeCameToDo(thing, hoob, glork);releaseGlork(glork);
releaseHoob (hoob)
releaseThing(thing);

This kind of thinking is freaking backwards, whether it’s instantiating objects as above or checking parameters. This is anxiety-driven coding; something might fail, so quick!! Bail out!! As the stomach settles move on to the next operation. Reading code like this makes me sick, I can feel the writer’s stomach cramps myself.

I do this:

Thing thing = createThing();if (thing != NULL)
{
Hoob hoob = createHoob();
if (hoob != NULL)
{
Glork glork = createGlork();
if (glork != NULL)
{
doWhatWeCameToDo(thing, hoob, glork);
releaseGlork(glork);
}
else
{
logger.error("no glork");
}
releaseHoob(hoob);
}
else
{
logger.error("no hoob");
}
releaseThing(thing);
}
else
{
logger.error("no thing");
}

Note the difference in the upper part of each example.

  • Each create is matched to a single release regardless of what happened between.
  • The execution flow is positive; error handling is in the else blocks and not in your face
  • The actual operation is easily located in the innermost block
  • if the objects are garbage-collected and the release calls are not necessary then they will be collected at end of scope
  • In the ER example there are 16 lines aside from curly braces before the real operation; in the non-ER example there are seven. You can see the critical part of the function on one small window; in the ER example you are looking mostly at error handling

It so happens that I wrote in C only a few years ago doing embedded work, in a modern garbage-collected language the release calls would not be there but the point is that the visible flow expects things to work and the failures are handled as else-blocks. The indentation allows easy brace-matching so don’t complain about that.

It’s not just a different way to write, it’s a different way to think; you code from the outside in instead of from the top down.

American Software Developer living in Vietnam. Classical musician (guitar, woodwinds), weightlifter, multilingual, misanthrope • XY

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store