[英]Java Conventions - Using Curly Braces to Isolate Code?
我很好奇這個。 我最近有了一個想法,即使用花括號來隔離代碼段以進行視覺組織,並將變量隔離到特定的 scope(如果只是為了防止它們在更大的函數中混淆 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....
}
請注意輕微的代碼清理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.