Golang : Metaprogramming example of wrapping a function




One of the most important mantras in programming is "DRY" or "Don't Repeat Yourself". Software developers should try to master the concept of metaprogramming to reduce the number of lines of codes and hopefully .... spend less time sitting/standing in front of computers and becoming healthier in the process.

Metaprogramming in the simplest term means .... creating functions to manipulate code such as modifying or generating or wrapping existing code to prevent or reduce chances of "DRY". Extra processes such as adding timing or logging functions can be turned into functions and use the functions for metaprogramming.

Let's consider this simple program that uses time package to calculate execution time.

 package main

 import (
 "fmt"
 "time"
 )

 func main() {
 startTime := time.Now()
 fmt.Println("Hello World")
 endTime := time.Now()

 fmt.Println("Time taken is about ----->> ", endTime.Sub(startTime))

 startTime = time.Now()
 fmt.Println("Goodbye World")
 endTime = time.Now()

 fmt.Println("Time taken is about ----->> ", endTime.Sub(startTime))
 }

Instead of repeating the startTime and endTime lines, we can optimize for a more elegant solution and solve this with metaprogramming.

 package main

 import (
 "fmt"
 "time"
 )

 type toBeWrapped func()

 func TimeTaken(function toBeWrapped) {
 startTime := time.Now()
 function()
 endTime := time.Now()
 fmt.Println("Time take is about ----->> ", endTime.Sub(startTime))
 }

 func main() {

 // anonymous or lambda function
 HWfunc := func() {
 fmt.Println("Hello World")
 }

 // wrap our anonymous function with TimeTaken function
 TimeTaken(HWfunc)

 // anonymous or lambda function
 GWfunc := func() {
 fmt.Println("Goodbye World")
 }
 TimeTaken(GWfunc)

 }

Hope this helps! Happy coding!





By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.


Advertisement