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
+10.4k Android Studio : Checkbox for user to select options example
+9.2k Golang : Accessing content anonymously with Tor
+12.3k Golang : Transform comma separated string to slice example
+18.1k Golang : How to get hour, minute, second from time?
+6.2k Golang : Break string into a slice of characters example
+27.1k PHP : Convert(cast) string to bigInt
+13.5k Golang : Gin framework accept query string by post request example
+10.6k Golang : Command line file upload program to server example
+17.8k Golang : Check if a directory exist or not
+8.5k Golang : Accept any number of function arguments with three dots(...)
+6k Golang & Javascript : How to save cropped image to file on server
+5.9k Golang : Process non-XML/JSON formatted ASCII text file example