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()
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)
}
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
}
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.
Top comments (0)