Shipping costs: changing carrier without breaking the code
The moment the code turns into a tangled mess
A cart holds three items, two delivery methods are offered, and the shipping cost calculation looks like a string of nested conditions. The code works, until the day a fourth carrier enters the picture. The method that calculates the shipping cost grows, a new branch appears, and the risk of introducing a regression goes up. A Dev.to article devotes a post to the Strategy pattern applied to e-commerce shipping in Java.
1. First observation: cascading conditions end up hiding the intent of the code
In the e-commerce example, each delivery method follows its own rules: maximum weight, deliverable country, lead time, flat or variable fees. Without Strategy, all of this lives in the same place, often in a `calculateShipping(Order order)` method containing a tree of `if`, `else if`, `else`. With every new provider, the developer has to open that method, understand all the branches so as not to break an existing case, then insert their own. With five providers and three weight zones, the method runs past a hundred lines and nobody reads it in full anymore.
Here is the situation before refactoring, in a simplified excerpt inspired by the Dev.to scenario:
public double calculateShipping(Order order) {
if (order.getCountry().equals("France")) {
if (order.getWeight() < 2) return 5.99;
else return 9.99;
} else if (order.getCountry().equals("Allemagne")) {
if (order.getWeight() < 3) return 7.99;
else return 12.99;
} else if (order.getCountry().equals("Espagne")) {
return 8.99;
}
return 0;
}
Touching one branch often forces a rewrite of several tests. The freeCodeCamp guide for beginners cites a class with multiple conditions as an example that violates the Strategy pattern.
2. Second observation: a behavior should not be a branch of an if
All the classes implement a shared interface, for example `ShippingStrategy` with a `calculate(Order order)` method. The calling code, often called the context, knows only that interface. It receives an already chosen strategy and executes it.
The Java Design Patterns site uses the analogy of a car navigation system. A GPS can calculate a route using several algorithms: fastest, shortest, most economical or most scenic. Each algorithm is a distinct strategy. The user, or an upper layer, selects the strategy at runtime.
Another example cited by Reactive Programming concerns authentication. An application can offer login by username and password, by OAuth, or by biometric fingerprint. Each of these methods is a strategy. It calls the `authenticate()` method of the injected strategy. A new authentication method can then be added without touching the main flow.
3. A step-by-step example: the e-commerce expedition refactored with Strategy
Let's return to the e-commerce scenario described by Dev.to. Before refactoring, the `ShippingCostCalculator` class probably contains a single method. This method examines the destination country, the parcel weight and the chosen delivery method. After refactoring, we get an interface and several concrete classes.
- Define the common interface: it contains the signature of the method that encapsulates the algorithm. For example, `double calculate(Order order)`.
- Create the concrete strategies: one class per carrier or per calculation rule. `StandardShipping`, `ExpressShipping`, `InternationalShipping`, each implements the interface and contains its own logic.
- Create the context: a `ShippingService` or `Checkout` class holds a reference of type `ShippingStrategy`. It does not know which concrete strategy is used.
- Replace the conditions: the method that previously chained the `if` statements becomes a simple call `strategy.calculate(order)`. The choice of strategy is moved to a single point, often a factory or a dependency injection.
- Inject the strategy: at runtime, the system selects the appropriate strategy (for example based on the delivery method chosen by the user) and passes it to the context.
After refactoring, the context code becomes:
public class ShippingService {
private ShippingStrategy strategy;
public ShippingService(ShippingStrategy strategy) {
this.strategy = strategy;
}
public double calculate(Order order) {
return strategy.calculate(order);
}
}
Each concrete strategy implements the interface with its own logic, without worrying about the others. Adding a new carrier boils down to creating a new `ChronopostStrategy` class and registering it in the factory. No change to the context is necessary, and the open/closed principle remains respected.
4. Third observation: the context does not need to know the details
In the car navigation example cited by Java Design Patterns, the navigation system does not know the difference between the shortest path algorithm and the fastest one. It only knows that it can request a route. An algorithm can be swapped on the fly, without recompiling the context.
On the testing side, each strategy is tested in isolation, without having to build a complex context. One can also create mock strategies to test the context, checking that it calls the method at the right time. The Reactive Programming site illustrates this idea with an authentication example: an application can offer several login methods (username/password, OAuth, biometric fingerprint).
5. What Strategy concretely changes in a project
Removing cascading conditions reduces the number of possible execution paths in a method, and therefore the cyclomatic complexity. The freeCodeCamp guide points out that the example violating the pattern becomes difficult to maintain, while the refactored version is more modular.
A strategy defined for an e-commerce operator can be reused in another context, for example in calculating return fees. Since it does not depend on a particular class, it can be plugged in elsewhere. For example, a file reader interface can offer strategies for reading text, CSV or JSON, without modifying the reading logic.
In a video game, each weapon is an attack strategy, and the character can change it at any time.
6. Comparison: Strategy against the classic alternatives
Two approaches often sit alongside Strategy: inheritance and cascading conditions.
| Approach | Advantages | Drawbacks | Typical use case |
|----------|-----------|---------------|---------------------|
| if/else conditions | Simple to write, fast for 2 or 3 cases | Explodes as cases grow, breaks the open/closed principle, hard to test | Prototype, small number of stable variants |
| Inheritance | Factors out common code in a parent class | Freezes behavior at compile time, risks deep hierarchies, cannot change at runtime | Behaviors that do not vary after instantiation |
| Strategy | Decouples the algorithm from the context, extensible, testable, changeable at runtime | More classes, slight indirection, sometimes overkill for a single algorithm | Families of interchangeable algorithms, variable business rules |
A single shipping cost formula that will never change does not need the pattern: a plain method covers it. Once several variants coexist or are expected to appear, the extra classes pay for themselves.
7. Checklist: implementing Strategy without getting it wrong
- [ ] Identify a behavior that changes depending on context (delivery, payment, authentication, routing).
- [ ] Check that the variants are numerous or unstable enough to justify the pattern.
- [ ] Define a minimal interface, with a single method if possible.
- [ ] Create one class per variant, each implementing the interface without unnecessary shared state.
- [ ] Change the context so it depends on the interface, not the concrete classes.
- [ ] Replace the conditions with a simple call to the strategy.
- [ ] Move the choice of strategy into a factory, a configuration or dependency injection.
- [ ] Test each strategy independently, then test the context with a fake strategy.
- [ ] Make sure adding a new strategy requires no change to the existing context.
8. Pitfalls to avoid
For three carriers, you create three classes plus an interface, four files in all. If the number of variants is small and stable, that is needless complexity. Another trap is dependence on context data. If a strategy needs access to private fields of the context class, you will have to either expose that data or pass a parameter object. That can weigh down the interface. The selection logic, too, must sit in one clearly identified place: scattered across several spots, it costs the pattern part of its value.
A melee weapon and a ranged weapon, for instance, can both be active for the same context. In that case you need a mechanism to switch strategies as the game goes on, often a setter or injection.
9. Back to the e-commerce cart: Friday evening
The opening scenario described a developer dreading the addition of a carrier on a Friday evening. With this approach, that task boils down to creating a new `ChronopostStrategy` class implementing the `ShippingStrategy` interface. Then you write the corresponding unit tests, then register that strategy in the factory or the injection container. The `ShippingService` class stays untouched, and the existing tests keep passing.
Further reading
- freeCodeCamp: beginner's guide with a code example that violates the Strategy pattern and then fixes it.
- Dev.to: concrete e-commerce shipping example in Java, with step-by-step refactoring.
- Java Design Patterns: description of the pattern with the car navigation system example.
- Reactive Programming: application example with several authentication methods.
