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
Tutorials
+12.4k Golang : Listen and Serve on sub domain example
+17.3k Golang : delete and modify XML file content
+20.8k Golang : How to force compile or remove object files first before rebuild?
+11.3k Golang : Handle API query by curl with Gorilla Queries example
+14.9k Golang : How to add color to string?
+20.8k Golang : Clean up null characters from input data
+7.1k Android Studio : How to detect camera, activate and capture example
+26k Golang : Get executable name behind process ID example
+17.7k Golang : Get all upper case or lower case characters from string example
+27.2k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+7.9k Golang : How To Use Panic and Recover
+7.2k Golang : Hue, Saturation and Value(HSV) with OpenCV example