Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
236: Decorator Pattern via Function Wrapping
A few years ago, I was reviewing a PR from a developer who was trying to debug a performance lag in our payment processing pipeline. He had manually added time.Now() and log.Printf calls to about fifteen different functions across three different packages. It worked, but the code was suddenly cluttered with "noise" that had nothing to do with payments and everything to do with telemetry. Every time he wanted to change the log format, he had to touch fifteen different files. It was a maintenance nightmare waiting to happen.
I sat him down and showed him how to pull that telemetry logic out into a wrapper. Instead of modifying the functions, we created a "decorator" that wrapped the functions. The look on his face was a mix of relief and annoyance that he'd spent four hours writing boilerplate that could have been handled by a single ten-line function. That's the power of the Decorator pattern in Go.
Wrapping Logic with Higher-Order Functions
In Go, the most elegant way to implement the Decorator pattern isn't through complex interface hierarchies, but through higher-order functions—functions that take other functions as arguments and return a new function. This allows you to "plug in" behavior before or after the core logic executes without the core function ever knowing it's being watched.
To do this, you first need a consistent function signature. If your functions all look different, you can't wrap them. Let's define a type for a generic operation that takes a string and returns an error:
type Operation func(string) error
Now, imagine we have a core function that actually does the work, like saving a record to a database. This function should stay "pure"—it only cares about saving the data, not about logging or timing:
func saveUser(name string) error {
fmt.Printf("Saving user %s to database...\n", name)
// Imagine actual DB logic here
return nil
}
To decorate this, we write a function that accepts an Operation and returns a new Operation. I usually think of this as creating a "shell" around the original logic:
func withLogging(next Operation) Operation {
return func(name string) error {
fmt.Printf("[LOG] Starting operation for: %s\n", name)
err := next(name)
fmt.Printf("[LOG] Finished operation for: %s. Error: %v\n", name, err)
return err
}
}
Composing Multiple Behaviors
The real magic happens when you realize these wrappers are composable. Since withLogging returns an Operation, you can pass the result of one wrapper into another. It's like an onion; each layer adds a bit of functionality before passing the request deeper into the core.
Let's add a timing wrapper to see this in action. I personally find this approach much cleaner than using an interceptor pattern or heavy-handed dependency injection for simple cross-cutting concerns:
func withTiming(next Operation) Operation {
return func(name string) error {
start := time.Now()
err := next(name)
fmt.Printf("[TIMER] %s took %v\n", name, time.Since(start))
return err
}
}
func main() {
// We wrap saveUser in timing, then wrap that result in logging
// The execution order will be: Logging -> Timing -> saveUser
decoratedSave := withLogging(withTiming(saveUser))
decoratedSave("Alice")
}
When you run this, the saveUser function remains blissfully unaware that it's being timed and logged. If you decide tomorrow that timing is too expensive for production, you just remove the withTiming wrapper from your initialization logic. You don't have to hunt through your business logic to delete time.Since calls.
📋 Practical Task
Build a Retrying API Call Decorator
You are building a client that calls a flaky third-party weather API. Instead of putting "retry" loops inside every single API function, you need to implement a Decorator.
Requirements:
- Define a function type
APIRequest func(string) error. - Create a base function
fetchWeather(city string) errorthat randomly returns an error (to simulate a flaky network). - Create a decorator function
withRetry(next APIRequest, attempts int) APIRequest. - The
withRetrydecorator should call the original function. If it returns an error, it should retry up to the specified number ofattemptsbefore finally giving up and returning the error. - In your
mainfunction, wrapfetchWeatherwithwithRetry(set to 3 attempts) and call it for a city of your choice.
There are no comments for now.