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

后端 未结 16 2209
梦谈多话
梦谈多话 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 05:51

    Relevance.

    Just because two variables are of type String does not mean they are closely related to each other.

    If the two (or more) variables are closely related by function, rather then variable type, then maybe they could be declared together. i.e. only if it makes sense for a reader of your program to see the two variables together should they actually be placed together

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

    Because in some languages, var2 and var3 in your example would not be strings, they would be variants (untyped).

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

    With separate lines, you have the opportunity to add a comment on each line describing the use of the variable (if it isn't clear from its name).

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

    I think that there are various reasons, but they all boil down to that the first is just less readable and more prone to failure because a single line is doing more than one thing.

    And all that for no real gain, and don't you tell me you find two lines of saved space is a real gain.

    It's a similar thing to what happens when you have

    if ((foo = some_function()) == 0) {
        //do something
    }
    

    Of course this example is much worse than yours.

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

    It is bad practice mostly when you can and want to initialize variables on the deceleration. An example where this might not be so bad is:

    string a,b;
    if (Foo())
    {
      a = "Something";
      b = "Something else";
    }
    else
    {
      a = "Some other thing";
      b = "Out of examples";
    }
    
    0 讨论(0)
  • 2020-12-06 06:00
    1. to be more apparent to you when using Version Control tools (covered by Michel)
    2. to be more readable to you when you have the simplest overflow/underflow or compile error and your eyes failed to point out the obvious
    3. to defend the opposite (i.e. multi-variable single-line declaration) has less pros ("code textual vertical visibility" being a singleton)
    0 讨论(0)
提交回复
热议问题