Skip to Content
Course content

236: Decorator Pattern via Function Wrapping

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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) error that randomly returns an error (to simulate a flaky network).
  • Create a decorator function withRetry(next APIRequest, attempts int) APIRequest.
  • The withRetry decorator should call the original function. If it returns an error, it should retry up to the specified number of attempts before finally giving up and returning the error.
  • In your main function, wrap fetchWeather with withRetry (set to 3 attempts) and call it for a city of your choice.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.