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
+25.2k Golang : Convert uint value to string type
+7.5k SSL : How to check if current certificate is sha1 or sha2 from command line
+14.5k Golang : Overwrite previous output with count down timer
+12.9k Golang : Get terminal width and height example
+8.2k Golang : HttpRouter multiplexer routing example
+29.5k Golang : Record voice(audio) from microphone to .WAV file
+7k Restart Apache or Nginx web server without password prompt
+7.3k Golang : Check to see if *File is a file or directory
+10k Golang : Test a slice of integers for odd and even numbers
+13.4k Golang : Read XML elements data with xml.CharData example
+4.9k Golang : Constant and variable names in native language
+17.4k Golang : Multi threading or run two processes or more example