Why do you not declare several variables of the same type on the same line?

后端 未结 16 2208
梦谈多话
梦谈多话 2020-12-06 05:41

Why is it bad practice to declare variables on one line?

e.g.

private String var1, var2, var3

instead of:

private          


        
相关标签:
16条回答
  • 2020-12-06 06:02

    Why is that bad practice? I don't think it is, as long as your code is still readable.

    //not much use
    int i, j, k;
    
    //better
    int counter, 
        childCounter, 
        percentComplete;
    
    0 讨论(0)
  • 2020-12-06 06:03

    Agree with edg, and also because it is more readable and easy for maintenance to have each variable on separate line. You immediately see the type, scope and other modifiers and when you change a modifier it applies only to the variable you want - that avoids errors.

    0 讨论(0)
  • 2020-12-06 06:06

    Generally it is, for the version control and commenting reasons discussed by others, and I'd apply that in 95% of all cases. however there are circumstances where it does make sense, for example if I'm coding graphics and I want a couple of variables to represent texture coordinates (always referenced by convention as s and t) then the declaring them as

    int s, t; // texture coordinates

    IMHO enhances code readability both by shortening the code and by making it explicit that these two variables belong together (of course some would argue for using a single point class variable in this case).

    0 讨论(0)
  • 2020-12-06 06:10

    To be honest I am not against it. I think that its perfectly feasible to group similar variables on the same line e.g.

    float fMin, fMax;

    however I steer clear when the variables are unrelated e.g.

    int iBalance, iColor;

    0 讨论(0)
提交回复
热议问题