DRY-ing Go/Golang’s error handling with underscores.

reinhart1010

Reinhart Previano K.

Posted on January 9, 2024

DRY-ing Go/Golang’s error handling with underscores.

The Go Programming Language, also preferred by others as Golang, doesn’t include the concept of Exceptions and try-catch like Java. This is why many functions and libraries built around it are meant to be written like this:

output, err := somelib.SomeCoolFunction()
Enter fullscreen mode Exit fullscreen mode

If you are writing simple programs with Go, there are many cases that you just don’t put much care on error-handling. If you, for example, just want the program to exit and informing the error message, you might most likely to do this:

data1, err := somelib.SomeCoolFunction()
if err != nil {
  log.Fatal(err)
}

data2, err := anotherlib.AnotherCoolFunction()
if err != nil {
  log.Fatal(err)
}

err := somelib.SaveTheseCoolData(data1, data2)
if err != nil {
  log.Fatal(err)
}
Enter fullscreen mode Exit fullscreen mode

Well, that’s bad if you try to place the exact same if conditions for every methods, just because you don’t want to take much care in handling errors. This is why I decided to simplify things by introducing two new functions, __(err) and ___(res, err)!

func __(err error) {
  if err != nil {
    log.Fatal(err)
  }
}

func ___[T interface{}](res T, err error) T {
  if err != nil {
    log.Fatal(err)
  }
  return res
}
Enter fullscreen mode Exit fullscreen mode

Completely good for “Don’t Repeat Yourself” (DRY). But remember, if you have more than one package, you will need to repeat writing the same functions to get the same convenience for every different package, because these underscore names are not considered as public functions.

💖 💪 🙅 🚩
reinhart1010
Reinhart Previano K.

Posted on January 9, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024