简体   繁体   English

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

[英]Java Conventions - Using Curly Braces to Isolate Code?

I'm curious about this.我很好奇这个。 I've recently had the idea of isolating segments of code using the curly braces for both visual organization and to isolate the variables to that specific scope (if only to keep them from cluttering the suggestions in Eclipse in larger functions).我最近有了一个想法,即使用花括号来隔离代码段以进行视觉组织,并将变量隔离到特定的 scope(如果只是为了防止它们在更大的函数中混淆 Eclipse 中的建议)。 For instance:例如:

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....
}

Does this affect performance?这会影响性能吗? Is it against convention?是否违反惯例? Would doing this be frowned upon in a professional environment?在专业环境中会不赞成这样做吗?

If you need to do that, you should break the block out into a method.如果你需要这样做,你应该把块分解成一个方法。

Further, comments are a code smell.此外,注释是一种代码味道。 In almost every case, if you have to comment your code, it's poorly written:几乎在每一种情况下,如果你必须注释你的代码,它就写得不好:

Turn your comment into a method name!将您的评论变成方法名称!

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;
}

Now your main code is readable!现在你的主要代码是可读的!

public void startInstall() {
    m_progress = 0;

    double succ_chance = determineChanceOfSuccess();

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

    // Do more stuff....
}

Note slight code clean up too.请注意轻微的代码清理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM