gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:37:49 29 4
gpt4 key购买 nike

我正在努力使它尽可能通用。假设在 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com