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

17

17

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

e.g.

private String var1, var2, var3

instead of:

private String var1;
private String var2;
private String var3;
Montespan answered 19/9, 2008 at 9:6 Comment(0)
T
11

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.

Thadeus answered 19/9, 2008 at 9:13 Comment(0)
A
22

In my opinion, the main goal of having each variable on a separate line would be to facilitate the job of Version Control tools.

If several variables are on the same line you risk having conflicts for unrelated modifications by different developers.

Aspirator answered 19/9, 2008 at 9:9 Comment(0)
C
20

In C++ :

int * i, j;

i is of type int *, j is of type int. The distinction is too easily missed.

Besides having them on one line each makes it easier to add some comments later

Century answered 19/9, 2008 at 9:13 Comment(1)
Found this question when reseaching for where the pointer to the star have to be bound: type or name side. The main resaons for the type side is consistency and in c++ the type is whats important. And a pointer is another type. But then this legacy c argument often comes up. In fact having each line declaring one variable is somewhere in the region of clean code principles, so @David, you put the main argument for multiple lines just in front of us and it is not visible.Featherstone
T
11

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.

Thadeus answered 19/9, 2008 at 9:13 Comment(0)
L
10

In C/C++, you also have the problem that the * used to indicate a pointer type only applies to the directly following identifier. So a rather common mistake of inexperienced developers is to write

int* var1, var2, var3;

and expecting all three variables to be of type 'int pointer', whereas for the compiler this reads as

int* var1;
int var2;
int var3;

making only var1 a pointer.

Lloyd answered 19/9, 2008 at 9:16 Comment(0)
D
6

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

Diageotropism answered 19/9, 2008 at 9:11 Comment(1)
Although wouldn't it be better to rename the variable in this case?Participation
S
5

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

Southland answered 19/9, 2008 at 9:6 Comment(0)
T
5

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;
Timbering answered 19/9, 2008 at 9:23 Comment(1)
Your "better" style is what I generally use in languages that require variable declaration. It's a bit more DRY while still maintaining readability.Alvardo
S
5

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

Savaii answered 19/9, 2008 at 10:0 Comment(1)
That is a great comment and should be fit right into clean code principles! Indeed if it is some basic counter or swap stuff, they should be in one line, they act together and there is no reason for different commens (a good name don't need them) and in version controls that line can't be touched from different sides without f*** up alttogether. In any other case multiple lines should be the default case. It increases the semantic separation even more AND supports easy skimming/reading.Featherstone
K
4

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;

Kinghood answered 19/9, 2008 at 9:15 Comment(0)
C
3

Here's my reasons:

  • Readability, easier to spot if you know there's only one on each line
  • Version control, less intra-line changes, more single-line additions, changes, or deletions, easier to merge from one branch to another
Cornhusking answered 19/9, 2008 at 9:12 Comment(0)
T
3

What about the case such as:

public static final int NORTH = 0,
                        EAST = 1,
                        SOUTH = 2,
                        WEST = 3;

Is that considered bad practice as well? I would consider that okay as it counters some of the points previously made:

  • they would all definitely be the same type (in my statically typed Java-world)
  • comments can be added for each
  • if you have to change the type for one, you probably have to do it for all, and all four can be done in one change

So in an (albeit smelly code) example, is there reasons you wouldn't do that?

Thereon answered 19/9, 2008 at 9:18 Comment(1)
one problem with this: if you add more variables and forget to change the semicolons into commas. ;)Cultism
C
1

Suppose you need to code in several languages, maybe C, C#, VBA, etc.

By adopting a more conservative stance, that is, splitting the declaration appropriately,

private String var1
private String var2
private String var3

you're really adopting a style which is a bit more universal. You'll get it right the first time, at least more often.

Further, a style like

private String var1, var2, var3

in VBA would implicitly declare var2 and var3 as Variant. The code would work because var2 and var3 would be, silently, variants. Convenient, but nasty.

Last and certainly least, splitting the declarations gives you a bit more freedom to possibly assign intial default values. Shorter code.

private String var1 = "plutonium";
private String var2 = "soft-shelled turtle";
private String var3 = "X5Jetstar";

or in VBA, something like

dim var1 as String: var1 = "plutonium"

I would always try to stick with decent coding habits which would spread around other languages.

Clo answered 11/6, 2023 at 7:43 Comment(1)
After reading the upper answers this also came into mind: Switching platforms makes this somewhat easier to spot patterns and just replace by line patterns.Featherstone
U
0

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.

Uam answered 19/9, 2008 at 9:10 Comment(0)
G
0
  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)
Gosport answered 19/9, 2008 at 9:16 Comment(0)
S
0

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";
}
Singhalese answered 19/9, 2008 at 9:18 Comment(0)
F
0

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

Froude answered 19/9, 2008 at 9:43 Comment(0)
C
0

while attempting this question https://www.interviewbit.com/problems/remove-element-from-array/

Method 1 gives Memory Limit exceeded for this code:

Type 1:

int i,j;

Type 2:

int i;
int j;

type 1: Gives Memory Limit Exceeded

int removeElement  (int* A, int n1, int B) 
{
    int k=0, i;
    for(i=0;i<n1;i++)
        if(A[i]!=B)
        {
            A[k]=A[i];
            k++;
        }    
    return k;
}

Whereas type 2 works perfectly fine

int removeElement  (int* A, int n1, int B) 
{
    int k=0;
    int i;
    for(i=0;i<n1;i++)
        if(A[i]!=B)
        {
            A[k]=A[i];
            k++;
        }    
    return k;
}
Coracorabel answered 22/8, 2018 at 9:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.