gpt4 book ai didi

Java 约定 - 使用大括号来隔离代码?

转载 作者:行者123 更新时间:2023-12-01 19:34:04 25 4
gpt4 key购买 nike

我对此很好奇。我最近想到使用大括号来隔离代码段,以进行可视化组织,并将变量隔离到特定范围(如果只是为了防止它们在较大的函数中混淆 Eclipse 中的建议)。例如:

public void startInstall()
{
boolean success = false;
m_progress = 0;

// Determine Chance of Success (This is isolated in curly braces)
{
double weight_total = 0;
double weight_sum = 0;
for(int i=0; i < Data.m_feature_selection.size(); i++)
{
if(Data.m_feature_selection.get(i))
{
int weight = Data.m_feature_weight.get(i);
weight_total += Math.abs(weight);
weight_sum += weight;
}
}
double succ_chance = (weight_sum / weight_total) + 0.15;
if(Math.random() <= succ_chance)
success = true;
}
// Do more stuff....
}

这会影响性能吗?是否违反惯例?在专业环境中这样做会被人皱眉吗?

最佳答案

如果您需要这样做,您应该将该 block 分解为一个方法。

此外,注释是一种代码味道。几乎在所有情况下,如果您必须对代码进行注释,那么它写得不好:

将您的评论变成方法名称!

double determineChanceOfSuccess() {
double weight_total = 0;
double weight_sum = 0;
for(int i=0; i < Data.m_feature_selection.size(); i++) {
if(Data.m_feature_selection.get(i)) {
int weight = Data.m_feature_weight.get(i);
weight_total += Math.abs(weight);
weight_sum += weight;
}
}
double succ_chance = (weight_sum / weight_total) + 0.15;
return succ_chance;
}

现在你的主要代码是可读的!

public void startInstall() {
m_progress = 0;

double succ_chance = determineChanceOfSuccess();

boolean success = Math.random() <= succ_chance;

// Do more stuff....
}

请注意轻微的代码清理。

关于Java 约定 - 使用大括号来隔离代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58475702/

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