Home >Web Front-end >JS Tutorial >Using Strategy Pattern to Avoid Overconditioning

Using Strategy Pattern to Avoid Overconditioning

Linda Hamilton
Linda HamiltonOriginal
2025-01-12 06:04:42736browse

A few weeks ago, I worked on solutions for the Globo Player, where it was necessary to activate and deactivate specific behaviors in the software during execution. This type of need is commonly solved with chained conditionals, such as if-else and switch, but this approach is not always ideal.

In this article, I present a solution that perfectly met this challenge and that can be applied to different programming scenarios.

Which strategy should I use?

Imagine that you have just arrived at an unknown destination. When leaving the airport, you have a few options to get to your hotel. The cheapest alternative is to rent a bike, but this would take more time. Taking a bus would be a little more expensive, but it would get you there more quickly and safely. Finally, renting a car would be the quickest option, but also the most expensive.

Usando Strategy Pattern para evitar condicionamento exagerado

The most important point in this situation is to understand that, regardless of the strategy chosen, the final objective is the same: getting to the hotel.

This analogy can be applied to software development. When we deal with scenarios where different processes seek to achieve the same objective, we can use the Strategy design pattern to help us.

When you program without a strategy...

Imagine that we need to develop a banking system capable of calculating fees based on the customer's account type, such as current, savings or premium. These calculations need to be performed at runtime, which requires an implementation that correctly directs the code flow to the appropriate calculation.

In principle, a common approach would be to use a simple structure of chained conditionals to solve the problem quickly and functionally:

class Banco {
  calcularTaxa(tipoConta, valor) {
    if (tipoConta === "corrente") {
      return valor * 0.02; // 2% de taxa
    } else if (tipoConta === "poupanca") {
      return valor * 0.01; // 1% de taxa
    } else if (tipoConta === "premium") {
      return valor * 0.005; // 0,5% de taxa
    } else {
      throw new Error("Tipo de conta não suportado.");
    }
  }
}

const banco = new Banco();
const taxa = banco.calcularTaxa("corrente", 1000); // Exemplo: R00
console.log(`A taxa para sua conta é: R$${taxa}`);

While this solution works well for simple scenarios, what happens if the bank needs to add five more account types in the future?

calcularTaxa(tipoConta, valor) {
  if (tipoConta === "corrente") {
    return valor * 0.02; // 2% de taxa
  } else if (tipoConta === "poupanca") {
    return valor * 0.01; // 1% de taxa
  } else if (tipoConta === "premium") {
    return valor * 0.005; // 0,5% de taxa
  } else if (tipoConta === "estudante") {
    return valor * 0.001; // 0,1% de taxa
  } else if (tipoConta === "empresarial") {
    return valor * 0.03; // 3% de taxa
  } else if (tipoConta === "internacional") {
    return valor * 0.04 + 10; // 4% + taxa fixa de R
  } else if (tipoConta === "digital") {
    return valor * 0.008; // 0,8% de taxa
  } else if (tipoConta === "exclusiva") {
    return valor * 0.002; // 0,2% de taxa
  } else {
    throw new Error("Tipo de conta inválido!");
  }
}

Now, the code starts to show serious limitations. Let's explore the problems with this approach:

1. Low scalability

Every time a new account type needs to be added, the calculateRate method needs to be modified. This continually increases the number of conditionals, making the code more complex and difficult to manage.

2. High dependency

The rate calculation logic is completely coupled to the calculateRate method. Changes to one type of account can inadvertently impact others, increasing the risk of introducing bugs.

3. Code repetition

Similar snippets, such as amount * fee, are duplicated for each account type. This reduces code reuse and violates the DRY (Don't Repeat Yourself) principle.

In the next step, we will see how the Strategy Pattern can solve these problems, promoting cleaner, scalable and modular code.

One strategy at a time!

To avoid the problems mentioned above, we will treat each account type as an isolated entity in the software. This is because each type of account has a specific fee calculation and may have other associated future behaviors.

Instead of creating a Bank class with a calculateRate method that solves all operations, let's create a class for each type of account:

class Banco {
  calcularTaxa(tipoConta, valor) {
    if (tipoConta === "corrente") {
      return valor * 0.02; // 2% de taxa
    } else if (tipoConta === "poupanca") {
      return valor * 0.01; // 1% de taxa
    } else if (tipoConta === "premium") {
      return valor * 0.005; // 0,5% de taxa
    } else {
      throw new Error("Tipo de conta não suportado.");
    }
  }
}

const banco = new Banco();
const taxa = banco.calcularTaxa("corrente", 1000); // Exemplo: R00
console.log(`A taxa para sua conta é: R$${taxa}`);

This ensures that each calculation operation is kept within a specific scope for your account type. Now, we have isolated behaviors focused on each type of account:

Usando Strategy Pattern para evitar condicionamento exagerado


Solution architecture based on strategies.

But, where will the desired account selection be located?

calcularTaxa(tipoConta, valor) {
  if (tipoConta === "corrente") {
    return valor * 0.02; // 2% de taxa
  } else if (tipoConta === "poupanca") {
    return valor * 0.01; // 1% de taxa
  } else if (tipoConta === "premium") {
    return valor * 0.005; // 0,5% de taxa
  } else if (tipoConta === "estudante") {
    return valor * 0.001; // 0,1% de taxa
  } else if (tipoConta === "empresarial") {
    return valor * 0.03; // 3% de taxa
  } else if (tipoConta === "internacional") {
    return valor * 0.04 + 10; // 4% + taxa fixa de R
  } else if (tipoConta === "digital") {
    return valor * 0.008; // 0,8% de taxa
  } else if (tipoConta === "exclusiva") {
    return valor * 0.002; // 0,2% de taxa
  } else {
    throw new Error("Tipo de conta inválido!");
  }
}

Note that, instead of creating chained decision structures (if-else), we chose to pass an account, strategy in the constructor of our Bank class. This allows the setConta method to select the desired account type at run time when instantiating the bank. The rate calculation will be performed through this.conta.calcularTaxa(valor).

class ContaCorrente {
  calcularTaxa(valor) {
    return valor * 0.02; // 2% de taxa
  }
}

class ContaPoupanca {
  calcularTaxa(valor) {
    return valor * 0.01; // 1% de taxa
  }
}

class ContaPremium {
  calcularTaxa(valor) {
    return valor * 0.005; // 0,5% de taxa
  }
}

With this model, we were able to apply the Strategy Pattern in a simple way, ensuring a more flexible, scalable and low-coupling implementation.

Can I use strategy in everything?

The Strategy Pattern is a powerful solution when you need to vary the behavior of an operation at runtime, without directly coupling the execution code to different conditions or types. This pattern is ideal for scenarios where the behavior of an operation may vary depending on the context and where the alternatives are independent of each other.

When to use the Strategy Pattern

  • Variant behaviors: When the behavior of a system needs to be changed dynamically depending on specific conditions (such as different account types in the banking example).
  • Avoid complex conditionals: When the decision logic is based on many flow control structures, such as multiple if-else or switch, which makes the code difficult to maintain.
  • Ease of maintenance and expansion: When you want to add new behaviors without modifying existing code, simply creating new strategy classes.
  • Behavior decoupling: When you want to isolate specific behaviors in different classes, making the code more modular and flexible.

By using Strategy, we guarantee that the code becomes cleaner, modular and flexible, in addition to promoting better maintenance and expansion of the system.

The above is the detailed content of Using Strategy Pattern to Avoid Overconditioning. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn