我对此很好奇。最近,我有了这样的想法:使用用于可视化组织的大括号来隔离代码段,并将变量分离到特定的范围(如果只是为了防止它们在更大的函数中混淆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....
}这会影响性能吗?这是违反惯例吗?在一个专业的环境中,这样做是否会受到反对呢?
发布于 2019-10-20 18:05:13
如果您需要这样做,您应该将这个块分解成一个方法。
此外,注释是一种代码气味。在几乎每一种情况下,如果您必须注释代码,那么代码编写得很糟糕:
将您的评论转换为一个方法名!
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....
}注意,轻微的代码清理也。
https://stackoverflow.com/questions/58475702
复制相似问题