You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
"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:
6
6
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"
8
8
9
+
El codigo que queria refactorizar era algo como esto (solo un ejemplo):
@@ -28,16 +29,15 @@ public int DoMathematicalOperation (string @operator, int a, int b)
28
29
throwException("You must pass a valid operator");
29
30
}
30
31
31
-
//METHODS FOR ADD, MULTIPLY AND DIVIDE
32
+
//METODOS PARA SUMAR, MULTIPLICAR Y DIVIDIR
32
33
```
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.
33
35
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.
35
37
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.
37
39
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:
41
41
42
42
```csharp
43
43
publicinterfaceIMathematicalOperation
@@ -46,7 +46,7 @@ public interface IMathematicalOperation
46
46
}
47
47
```
48
48
49
-
Now, there is the 3 implementations:
49
+
Ahora tenemos estas 3 implementaciones:
50
50
51
51
```csharp
52
52
publicclassAddOperation : IMathematicalOperation
@@ -80,8 +80,7 @@ public class DivideOperation : IMathematicalOperation
80
80
}
81
81
}
82
82
```
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?
85
84
86
85
```csharp
87
86
publicinterfaceIMathematicalOperation
@@ -130,9 +129,9 @@ public class DivideOperation : IMathematicalOperation
130
129
}
131
130
```
132
131
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.
134
133
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.
136
135
137
136
```csharp
138
137
publicclassMathematicalOperationResolver
@@ -156,9 +155,9 @@ public class MathematicalOperationResolver
156
155
}
157
156
```
158
157
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.
160
159
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:
@@ -169,6 +168,6 @@ public int DoMathematicalOperation(string @operator, int a, int b)
169
168
}
170
169
```
171
170
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.
0 commit comments