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
99: The Strategy Pattern in Go
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
ShippingStrategyinterface with a methodCalculateCost(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
ShippingCalculatorstruct that holds aShippingStrategyand a methodGetTotal(weight float64) float64that uses the strategy to return the final cost. - In your
mainfunction, demonstrate swapping the strategy at runtime for a 10kg package to show that theShippingCalculatorproduces different results based on the injected strategy.
There are no comments for now.