IntelliJ IDEA
 
Get IntelliJ IDEA
You are viewing the documentation for an earlier version of IntelliJ IDEA.

Tutorial: Replace Conditional Logic with Strategy Pattern

Last modified: 11 February 2024

When you have a method with lots of conditional logic (that is, if statements), you're asking for trouble. Conditional logic is notoriously difficult to manage, and may cause you to create an entire state machine inside a single method.

Here's a short example. Let's say, there is a method that calculates insurance costs based on a person's income:

Let's analyze this example. Here we see the four "income bands widths", separated into four calculation strategies. In general, they conform to the following formula:

Our goal is to provide separate classes to calculate each strategy, and transform the original class to make it more transparent.