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
+9.2k Golang : ffmpeg with os/exec.Command() returns non-zero status
+7.8k Golang : Metaprogramming example of wrapping a function
+10.7k Golang : How to determine a prime number?
+4.3k JavaScript : Rounding number to decimal formats to display currency
+16k Golang : Check if a string contains multiple sub-strings in []string?
+11.8k Golang : Encrypt and decrypt data with x509 crypto
+7.2k Golang : Command line ticker to show work in progress
+12.6k Golang : Handle or parse date string with Z suffix(RFC3339) example
+7.6k Golang : Get all countries phone codes
+13.1k Golang : reCAPTCHA example
+12.9k Generate salted password with OpenSSL example
+10.2k Golang : Underscore string example