There were times when I found myself needing to write several db queries, each with 2 or 3 possible errors that needed checking, each with its own relevant variables to initialize, etc. And as I was writing this code I found it difficult to physically focus on the code to understand where I was in my logic.

In the past I would have extracted these separate queries into their own function to “clean up” the main routine.

More recently, though, I’ve taken to just using curly-brackets {} to organize my code.

Why?

Well, keep in mind the goal is to make the function easier to read. A set of {} accomplishes this nicely. And instead of a function name, I can just place an easier-to-read comment above the block.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21

func someLongRouting() {

  // start main routine code...

  // Now I have to do some sub-routine here...
  someVarNeededForParentFunction := []string{}
  {
    someVarNeededOnlyForThisBlock := ""
    
    someVarNeededForParentFunction = append(someVarNeededForParentFunction, someVarNeededOnlyForThisBlock)
  }

  // Now I need to do this other thing.
  // And for this other thing, I may need a longer comment.
  // Moving all this to another function is really disruptive 
  // when you're just trying to understand the main routine.
  {}

}

Of course, if one of those blocks contains steps that need to be reused elsewhere, that code block can easily be pulled out into a separate function, though this should be done with care to avoid needlessly sharing code.

With a simple {} block, I get all this:

  • code that is easily collapsed by the IDE / text editor
  • easy and clear grouping of code within the function
  • a comment above the block that can be easier to read than a function name
  • the freedom to make my comments as verbose as required, and keep them in context
  • easy access to variables within the parent function’s scope

When extracting to a one-off function, I get this:

  • a function that is used in only one place
  • comments and code far from their context
  • the misleading impression that the function code can be used in other contexts, when that isn’t the case (yet) and likely won’t be
  • the annoying problem of being directed all over the file just to understand a single parent routine

The Moral of the Story

Not everything needs to be a function, so I encourage you to give simple {} blocks a try. I think you’ll enjoy the simplicity and freedom it brings.