gpt4 book ai didi

c# - 嵌套的 if 条件 vs 多个分离的 if 条件,每个条件都有 return 语句

转载 作者:行者123 更新时间:2023-12-04 17:36:58 27 4
gpt4 key购买 nike

下面两个函数中最专业的代码风格是什么?

如果函数变得更复杂和更大,例如有 20 个检查怎么办?

注意:每次检查后我都需要做一些事情,所以我不能将所有内容连接到一个 if 语句中,例如:

if (vehicle.isBus) && (vehicle.numberOfWheels == 6) && (vehicle.motorVersion == 2019)

//first alternative
public bool validate(Vehicle vehicle)
{
if(vehicle.isBus)
{
//do some stuff here related to vehicle.isBus
if (vehicle.numberOfWheels == 6)
{
//do some stuff here related to vehicle.numberOfWheels
if (vehicle.motorVersion == 2019)
{
//do some stuff here related to vehicle.motorVersion
return true;
}
}
}
return false;
}

//second alternative
public bool validate(Vehicle vehicle)
{
if (!vehicle.isBus)
{
return false;
}
//do some stuff here related to vehicle.isBus

if (vehicle.numberOfWheels != 6)
{
return false;
}
//do some stuff here related to vehicle.numberOfWheels

if (vehicle.motorVersion != 2019)
{
return false;
}
//do some stuff here related to vehicle.motorVersion

return true;
}

最佳答案

我遵循的一个黄金法则是 避免嵌套 尽我所能。

使用使代码更具可读性和可理解性的方法。对于仅两种情况,第一种方式更具逻辑性和可读性。如果有 5 个或 6 个条件与 &&, || 相关联,情况可能不再如此和 !。

因此,当检查次数为 5+ 时,您应该更喜欢 第二种选择。

注意:没有每个调用返回的多个 if 意味着 2 个或多个 if 可能为真。

关于c# - 嵌套的 if 条件 vs 多个分离的 if 条件,每个条件都有 return 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56356190/

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