Skip to content

Commit a9877cf

Browse files
author
Carlos
authored
translation to spanish (spelling check pending)
1 parent dcf5b19 commit a9877cf

File tree

1 file changed

+17
-18
lines changed

1 file changed

+17
-18
lines changed

cjdelgado/PatronEstrategia/readme.md

+17-18
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
# No more nested conditionals, embrace the strategy pattern
1+
# No mas condicionales anidados, abraza el patrón estrategia
22

3-
Some days ago, a team partner asked in our chat how to resolve the following situation:
3+
[English version](https://www.carlosjdelgado.com/no-more-nested-conditionals-embrace-the-strategy-pattern/)
44

5-
"I have a controller calling a class, depending of the value of parameters passed to the controller the called method can make an action or another"
5+
Hace algunos dias un compañero de equipo formuló la siguiente pregunta en nuestro chat:
66

7-
The code that him want to refactor was something like this (is just an example) :
7+
"Tengo un controller que llama a una clase, dependiendo del valor del parametro que se le pasa al controller el metodo al que se llama puede hacer una cosa u otra"
88

9+
El codigo que queria refactorizar era algo como esto (solo un ejemplo):
910

1011
```csharp
1112
public int DoMathematicalOperation (string @operator, int a, int b)
@@ -28,16 +29,15 @@ public int DoMathematicalOperation (string @operator, int a, int b)
2829
throw Exception("You must pass a valid operator");
2930
}
3031

31-
//METHODS FOR ADD, MULTIPLY AND DIVIDE
32+
//METODOS PARA SUMAR, MULTIPLICAR Y DIVIDIR
3233
```
34+
¿Quien no se ha encontrado nunca en esta situación? El product owner necesita una nueva funcionalidad para la aplicación, pero esta funcionalidad tiene algunas excepciones que cambian todo el comportamiento para algunos casos. Por ejemplo, tienes un servicio de busqueda de vuelos que usa un servicio externo para devolver todos los vuelos disponibles en un dia, pero hay algunas rutas que usan otro servicio para obtener esos vuelos, en este caso el comportamiento cambia completamente.
3335

34-
Who had never been in this situation? The product owner needs a new feature for the application, but this feature has some exceptions that changes all over the behavior in some cases. For example, you have a flight search service that uses an external service that gives all the flights available on a date, but have some routes that uses another service for getting these flights, in this case the behavior changes completely.
36+
Otro caso puede ser si cambias una funcionalidad pero el product owner quiere que este inactiva en el entorno de produccion hasta que el departamento de marketing (por ejemplo) lo apruebe, en ese caso querras usar una feature flag en tus settings que cambian el comportamiento.
3537

36-
Another case can be if you change a functionality but the product owner wants to be inactive in production enviroments until marketing department (for example) approves it, in this case you want to use a feature flag in your settings file that changes the behavior.
38+
Volviendo a nuestro ejemplo anterior es obvio que hay mas de una implementacion de una operacion matematica con 2 operadores, el codigo anterior no respeta la S de los principios SOLID porque esta asumiendo mas de una responsabilidad al mismo tiempo (sumar, multiplicar y dividir), puede ser refactorizado separandolo para tener una implementación por operacion matematica usando una interface como molde.
3739

38-
Going back to our previous example is obvious that there are more than one implementation of a mathematical operation with two operators, The previous code does not respect the S of the SOLID principles because it is taken more than one resposability at once (Add, Multiply and divide), it can be refactored isolating to an implementation by mathematical operation and using an interface as shape.
39-
40-
There is the base interface of our refactor:
40+
Esta es la interface base de nuestro refactor:
4141

4242
```csharp
4343
public interface IMathematicalOperation
@@ -46,7 +46,7 @@ public interface IMathematicalOperation
4646
}
4747
```
4848

49-
Now, there is the 3 implementations:
49+
Ahora tenemos estas 3 implementaciones:
5050

5151
```csharp
5252
public class AddOperation : IMathematicalOperation
@@ -80,8 +80,7 @@ public class DivideOperation : IMathematicalOperation
8080
}
8181
}
8282
```
83-
84-
Having this scenario is easy to implement the strategy pattern, remember that an operation depends of operator symbol passed (+, *, /) so, why not to present the operator as a new property in each implementation?
83+
Sobre este escenario es facil de implementar un patrón estrategia, recuerda que cada operación depende del simbolo de operador que se le pase (+, *, /) entonces, ¿porque no presentar el operador como una nueva propiedad en cada implementacion?
8584

8685
```csharp
8786
public interface IMathematicalOperation
@@ -130,9 +129,9 @@ public class DivideOperation : IMathematicalOperation
130129
}
131130
```
132131

133-
It's time to add a new class in the ecuation; the resolver.
132+
Es el momento de añadir una nueva clase en la ecuación: el resolver.
134133

135-
The resolver of this case has the responsibility to give the correct implementation of an mathematical operation taking the operator symbol as parameter.
134+
El resolver de este caso tiene la responsabilidad de devolver la implementación correcta de una operación matematica a partir del simbolo de operador pasado como parametro.
136135

137136
```csharp
138137
public class MathematicalOperationResolver
@@ -156,9 +155,9 @@ public class MathematicalOperationResolver
156155
}
157156
```
158157

159-
Note that this is just an example, you can pass all the mathematical implementations as a list using your favorite DI system.
158+
Ten en cuenta que esto es solo un ejemplo, puedes pasar todas las implementaciones en una lista usando tu sistema favorito de DI.
160159

161-
With your resolver implemented then you can refactor the original code and the result would be like this:
160+
Con tu resolver implementado entonces puedes refactorizar el codigo original, y el resultado quedaría tal que asi:
162161

163162
```csharp
164163
public int DoMathematicalOperation(string @operator, int a, int b)
@@ -169,6 +168,6 @@ public int DoMathematicalOperation(string @operator, int a, int b)
169168
}
170169
```
171170

172-
You see? All the nested conditionals has been removed and the code has become more maintainable, take in mind when you find this situation the next time!
171+
Has visto? todos los condicionales anidados se han eliminado y el codigo ahora es mas mantenible, ten esto en cuenta cuando vuelvas a encontrarte con esta situación.
173172

174173
Happy coding!

0 commit comments

Comments
 (0)