If you have been in the IT industry long enough, you may still remember that about 10 years ago, when design patterns were all the rage, there was a counter "if"
movement.
The so-called counter- "if"
movement actually exaggerated "if"
the problems caused by the statement. For example, the questions raised at the time were:
- The code is not easy to maintain, especially when
if
thereelse
is a lot of code in it if
When thereelse if
are too many branches, the code is difficult to read and modify.- When reading
if
the code contained in it, you must simulate its execution in your own mind, which consumes your mental energy. - ... ... etc
These problems do exist, but to completely ban if
them because of these would be too extreme and would lead to giving up eating due to choking.
Branches and loops in code are inevitable. if
After a complete ban, more complex and outrageous code will be produced at some point.
Therefore, in the end, this anti "if"
-movement also died out.
However, in "if"
order create some alternatives, I have selected three that are worth looking at for your reference.
There are many other solutions that are not very reliable, so I won’t go into details one by one.
1. Split into multiple methods
This refactoring "if"
method is to encapsulate each branch into an independent method.
for example:
python
Copy code
def select_model(is_regression=True): if is_regression: print("选择【回归】模型") else: print("选择【分类】模型") # 测试代码 select_model(True) select_model(False) # 运行结果 选择【回归】模型 选择【分类】模型
In the example, the method select_model
uses is_regression
parameters to determine which model to call.
After refactoring:
python
Copy code
def select_regression(): print("选择【回归】模型") def select_classifier(): print("选择【分类】模型") # 测试代码 select_regression() select_classifier() # 运行结果 选择【回归】模型 选择【分类】模型
Split the original method into two new methods "if"
and it disappears.
2. Change to polymorphism
If there are many branches in a function, such as:
python
Copy code
def cry(animal): if animal == "dog": print("{} :汪汪~".format(animal)) elif animal == "cat": print("{} :喵喵~".format(animal)) elif animal == "sheep": print("{} :咩咩~".format(animal)) elif animal == "cow": print("{} :哞哞~".format(animal)) else: print("无法识别动物:{}".format(animal)) # 测试代码 cry("dog") cry("cat") cry("sheep") cry("cow") # 运行结果 dog :汪汪~ cat :喵喵~ sheep :咩咩~ cow :哞哞~
cry
The function determines the output content based on different parameters.
If there are many branches and there is a lot of code in each branch, it will be more difficult to maintain.
For the above "if"
situation where there are many branches, polymorphism can be used to transform it.
That is, an abstract class is encapsulated, which contains abstract methods cry
, and then different animals inherit the abstract class to implement their own cry
methods.
python
Copy code
from abc import ABCMeta, abstractclassmethod class Animal(metaclass=ABCMeta): def __init__(self, name) -> None: self.name = name @abstractclassmethod def cry(self): pass class Dog(Animal): def __init__(self) -> None: super().__init__("dog") def cry(self): print("{} :汪汪~".format(self.name)) class Cat(Animal): def __init__(self) -> None: super().__init__("cat") def cry(self): print("{} :喵喵~".format(self.name)) class Sheep(Animal): def __init__(self) -> None: super().__init__("sheep") def cry(self): print("{} :咩咩~".format(self.name)) class Cow(Animal): def __init__(self) -> None: super().__init__("cow") def cry(self): print("{} :哞哞~".format(self.name)) # 测试代码 animal = Dog() animal.cry() animal = Cat() animal.cry() animal = Sheep() animal.cry() animal = Cow() animal.cry() # 运行结果 dog :汪汪~ cat :喵喵~ sheep :咩咩~ cow :哞哞~
3. Inline conditional judgments
For more complex conditional judgments, inline methods can be used to improve them.
For example, a slightly complex judgment is constructed below:
python
Copy code
def complex_judge(foo, bar, baz): if foo: if bar: return True if baz: return True else: return False # 测试代码 print(complex_judge(True, True, False)) print(complex_judge(True, False, False)) print(complex_judge(False, True, True)) # 运行结果 True False True
Writing this way is not only difficult to read, but also troublesome when adding or modifying judgment conditions.
After modifying it inline (that is, using and
and or
), it is much simpler.
python
Copy code
def complex_judge(foo, bar, baz): return foo and bar or baz # 测试代码 print(complex_judge(True, True, False)) print(complex_judge(True, False, False)) print(complex_judge(False, True, True)) # 运行结果 True False True
4. Summary
The counter- "if"
movement has long since ended, and "if"
it seems absurd to completely abandon it, but this cannot be completely denied. "if"
Statements will affect the smooth flow of thought when reading the code, "if"
so it is necessary to maintain a cautious attitude towards the use of the code.