Quata 5: Conscious Coding

feature image

Quata 5: Conscious Coding

First off, I’d like to apologize for the long delay between the previous quata and this one. Life got in the way, in a good way, I would say. I found time to breathe tonight, and is there a better way to spend it than creating a new quata?

I won’t even attempt to give an introduction to this one lest I give away what it’s all about. I’ll let you look at the following code snippet first.

List<Pet> pets = readPetsFromDatabase(ownerId);
if (isAuthorized(userId)) {
  for (Pet pet: pets) {
} else {
  throw new UnauthorizedException(userId, ownerId);

Okay, what did you find?

Correct (because my readers are all smart)! Line 1 didn’t have to be line 1. It should have been inside the if-block.

While it may seem obvious to some, I’ve seen this kind of mistake made a lot. As developers, we need to be conscious (hence, the title of this post) of where we place our statements. I could have used the title “Correct Placement”, but then, it would have been too obvious.

Correct placement is important, for readability and/or, in this case, for performance reasons. You do not want to do the DB read unless necessary. If the user is not authorized, you would have wasted that read, not to mention the memory you allocated for the collection.

I’ll probably use the title “Conscious Coding” a lot for future quick quatas like this, where a more specific title would ruin the surprise.

Leave a Reply

Your email address will not be published. Required fields are marked *

Post navigation

Previous Post :