search
HomeWeb Front-endJS TutorialUsing Strategy Pattern to Avoid Overconditioning

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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software