Java 惯例 - 使用大括号隔离代码?
Java Conventions - Using Curly Braces to Isolate Code?
我很好奇这个。我最近有了使用大括号隔离代码段的想法,既可以进行可视化组织,也可以将变量隔离到特定范围(如果只是为了防止它们在 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....
}
这会影响性能吗?这违反惯例吗?在专业环境中这样做会让人不悦吗?
如果你需要这样做,你应该把这个块分解成一个方法。
此外,注释是一种代码味道。几乎在所有情况下,如果您必须注释您的代码,那说明它写得不好:
把你的评论变成方法名!
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....
}
注意轻微的代码清理。
我很好奇这个。我最近有了使用大括号隔离代码段的想法,既可以进行可视化组织,也可以将变量隔离到特定范围(如果只是为了防止它们在 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....
}
这会影响性能吗?这违反惯例吗?在专业环境中这样做会让人不悦吗?
如果你需要这样做,你应该把这个块分解成一个方法。
此外,注释是一种代码味道。几乎在所有情况下,如果您必须注释您的代码,那说明它写得不好:
把你的评论变成方法名!
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....
}
注意轻微的代码清理。