Skip to Content
Course content

99: The Strategy Pattern in Go

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

You’ve probably encountered a situation where your code is riddled with switch statements that seem to grow every time a new business requirement lands on your desk. I've seen this happen a dozen times in payment gateways or pricing engines. You start with two options, then four, and suddenly you have a 200-line function that is a nightmare to test because every time you add a new "case," you risk breaking the existing ones.

The Switch Statement Trap

Let's imagine we're building a checkout system for an e-commerce store. We need to apply different types of discounts: a flat amount off, a percentage off, or maybe no discount at all. The naive way to handle this is to pass a "type" string or an enum into a function and let a switch block handle the math.

type Order struct {
    Total float64
}

func ApplyDiscount(order Order, discountType string, value float64) float64 {
    switch discountType {
    case "flat":
        return order.Total - value
    case "percentage":
        return order.Total * (1 - value/100)
    case "none":
        return order.Total
    default:
        return order.Total
    }
}

At first glance, this is fine. It's readable and it works. But here is where it breaks: the moment your marketing team decides to add a "Buy One Get One" or a "Tiered Loyalty" discount, you have to go back into this specific function and modify it. In a large codebase, this ApplyDiscount function might be buried in a core package. Every time you touch it, you're risking a regression in the checkout flow. You're violating the Open/Closed Principle—your code should be open for extension, but closed for modification.

Decoupling Logic with Interfaces

This is where the Strategy Pattern comes in. Instead of the function deciding how to calculate the discount based on a flag, we define an interface that represents the action of discounting. We move the logic out of the switch statement and into separate, dedicated types. I like to think of this as swapping out a tool in a toolkit; the checkout process just knows it needs a "discount tool," and it doesn't care which one it's holding.

type DiscountStrategy interface {
    Calculate(total float64) float64
}

type FlatDiscount struct {
    Amount float64
}

func (f FlatDiscount) Calculate(total float64) float64 {
    return total - f.Amount
}

type PercentageDiscount struct {
    Percent float64
}

func (p PercentageDiscount) Calculate(total float64) float64 {
    return total * (1 - p.Percent/100)
}

type NoDiscount struct{}

func (n NoDiscount) Calculate(total float64) float64 {
    return total
}

Now, our order processor doesn't need a switch statement. It just asks the strategy to do its job.

type Checkout struct {
    DiscountStrategy DiscountStrategy
}

func (c *Checkout) FinalPrice(total float64) float64 {
    return c.DiscountStrategy.Calculate(total)
}

What this actually costs you

I won't tell you this is a magic bullet, because it isn't. The trade-off here is complexity. You've gone from one simple function to multiple structs and an interface. For a project that will truly only ever have two discount types, the Strategy Pattern is overkill. It adds "boilerplate" and forces the reader to jump between different types to see the full picture.

However, the payoff is massive for maintainability. If you need to add a "Seasonal Sale" discount, you just create a new struct that implements Calculate. You don't touch the Checkout struct, you don't touch the existing discount types, and you can write a unit test for the new strategy in total isolation. You've shifted the burden from "modifying existing code" to "adding new code," which is almost always the safer bet in a professional environment.




📋 Practical Task

Build a Multi-Carrier Shipping Calculator

You are tasked with implementing a shipping cost calculator for a logistics app. The app needs to support different shipping carriers, each with its own pricing logic. Instead of using a switch statement to determine the cost based on the carrier name, implement this using the Strategy Pattern.

Requirements:

  • Create a ShippingStrategy interface with a method CalculateCost(weight float64) float64.
  • Implement three strategies:
    • FedEx: Costs $5.00 base + $1.50 per kg.
    • UPS: Costs $7.00 base + $1.20 per kg.
    • DHL: Costs $10.00 flat rate regardless of weight.
  • Create a ShippingCalculator struct that holds a ShippingStrategy and a method GetTotal(weight float64) float64 that uses the strategy to return the final cost.
  • In your main function, demonstrate swapping the strategy at runtime for a 10kg package to show that the ShippingCalculator produces different results based on the injected strategy.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.