c++ - 建议对以下形式的 if 语句进行重构?

标签 c++ if-statement refactoring theory

我正在努力使它尽可能通用。假设在 if 语句中,我正在检查某个 bool 表达式 A 是否为真。假设存在 A 为真的特定情况,A.a 和 A.b,它们是互斥的。另一个 bool 表达式B也是如此。那么,考虑如下代码:

if (A) {
  if (A.a) {
    somethingSpecificToAa();
    foo();
  }
} else if (B) {
  if (B.a) {
    somethingSpecificToBa();
    foo();
  }
} else {
    foo();
}

在我的实际代码中,foo() 不是单个函数,而是多行长代码。重复这么多次它们对我来说似乎很臭,所以我认为需要进行一些重构。

因为 foo() 在以下情况下执行:

  • A.a 为真
  • B.a 为真
  • A 和 B 都不正确

我想到了以下几点:

if (A.a) {
  somethingSpecificToAa();
} else if (B.a) {
  somethingSpecificToBa();
}

if (A.a || B.a || !(A || B)) {
  foo();
}

应该有相同的行为。这是最好的方法吗?请注意,第二个示例的第二个 if 语句中的条件实际上非常长,这就是为什么我的代码仍然看起来像第一个示例的原因(我讨厌将单个 if 分成几行.) 我还考虑过制作一个返回 bool 的 lambda,它等同于 A.a || B.a || !(A || B) 并将 lambda 代入第二个 if 语句。或者,我可以保留第一个示例的结构,但将每个 foo() 的许多行替换为一个 (void) lambda 来做同样的事情,尽管我我不确定这能解决气味。

在这一点上我是否过度设计,考虑 lambda?哪种方法最适合维护干净的代码?

编辑:似乎我让它通用了。我正在处理 STL 容器,而不是我自己的类,一个更“准确”的例子是:

int shirtACleanliness = calculateCleanliness(shirtA);
if (itemsToWash.contains(shirtA)) { //itemsToWash is a std::set
  if (shirtA.cleanliness > shirtACleanliness) {
    itemsToWash.erase(shirtA);
    shirtA.cleanliness = shirtACleanliness;
    itemsToWash.insert(shirtA); //the set is ordered on cleanliness, so this re-inserts in the correct position
    doSomeOtherStuff(shirtA);
  }
} else if (itemsToDry.contains(shirtA)) { //itemsToDry is a std::vector
  if (shirtA.cleanliness > shirtACleanliness) {
    itemsToDry.erase(shirtA);
    shirtA.cleanliness = shirtACleanliness;
    itemsToWash.insert(shirtA);
    doSomeOtherStuff(shirtA);
  }
} else {
  shirtA.cleanliness = shirtACleanliness;
  itemsToWash.insert(shirtA);
  doSomeOtherStuff(shirtA);
}
//am aware aware contains() is not a method for either type
//and std::vector does not have erase() by value, this is just conceptual

最佳答案

根据您最近的评论,这里有一些可能符合您的用例的伪代码。

Element* element=nullptr;

if(vectorA.contains(X)){
   element = vectorA.get(X);
}else if(setB.contains(X)){
   element = setB.get(X);
}

if(element != nullptr && element->a){
   something(element);
}

if(element == nullptr || element->a){
    foo();
}

关于c++ - 建议对以下形式的 if 语句进行重构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55595060/

相关文章:

java - 在 Java 中使用 .equals()、.isEmpty() 和 .length() 检查空字符串

Ifs 重构帮助

c++ - 按值返回的函数的 return 语句中的初始化

c++ - 如何在 Qt 中的后续函数调用中访问在函数内创建的小部件

c++ - 如何根据C++中vector的内容使用std::move移动元素?

c - 有没有重构工具可以自动将大函数拆分成小函数?

c++ - 如何使用 C++ 和 SFML 创建自己的类

Android在编译二进制文件时重建静态库

c++ - Python 导入和使用单元格(带有 linux .so 文件)

java - 如果语句不等于