Using 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.
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:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
