This post reminds me of part of a "how to write clean code" and one of the challenges that the speaker proposed was to not use if statements on behavioral code. Obviously if statements on logical code is only (for lack of a better word) logical. So what this implies is that you would use polymorphic classes to give you the desired output. so as a super simple example i'll use the standard math example.
consider this code
public int SomeFunction()
{
int a=3;
int b=4;
int c;
//some logical operations
//that gives a value to c
switch(c)
{
case 1:
return a+b;
case 2:
return a-b;
case 3:
return a*b;
case 4:
return a^b;
default:
return 0;
}
}
as you can see from this code it does 2 things. Which doing more than one thing breaks the single responsibility principle. And although this is a simple example readability is not that impaired.
So a suggested way to fix this is to use a factory for the logic, and polymorphism for the operations. This would work out good because then everything can stick with the SRP, and makes debugging a little bit easier. Keep in mind because of how simple this example is it may feel like it is too complicated of a process, but a principle is simple idea that you can build off of. So lets build this. First our polymorphic class, we'll make a parent class called MathOperator
. it has a constructor that takes 2 numbers, and has a abstract method Operate
that returns a number. Next we make a MathFactory
. This class has nothing but static methods to get what we desire. One of the methods is GetProperMathOperator(int)
. It would replace the switch statement in the previous example with var mathOperation = MathFactory.GetProperMathOperator(c);
then we can simply just return mathOperation.Operate();
so our code would look something like this
public int SomeFunction()
{
int c;
//some logical operations
//that gives a value to C
var mathOperation = MathFactory.GetProperMathOperator(c);
mathOperation.SetValues(3,4);
return mathOperation.Operate();
}
but for testing purposes that code is a little difficult because this class depends on 2 other classes. So it would be better to take that code out and move it to the calling class. So to make it easier to test this function we would want to modify the method to ask for the proper MathOperator. Now you just set the values to what you need, and return the operatored number.
public int SomeFunction(MathOperator mathOperation)
{
mathOperation.SetValues(3,4);
return mathOperation.Operate();
}
So does this answer the OP's question? not directly. But since his code looks more like it is an abbreviated example of what his code really does, then I would think that he could use this principle to refactor his code into something that is a little cleaner, and would make the function easier to test and debug.
a
,b
, andv
represent? The clever way is often the wrong way. \$\endgroup\$v=CheckForSomeVariable()
and that will make my code easier to read. That is personal preference though. \$\endgroup\$