Craig Angus
Craig Angus

Reputation: 23198

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

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;

Upvotes: 17

Views: 18849

Answers (17)

Bill Early
Bill Early

Reputation: 181

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.

Upvotes: 1

jaskirat singh
jaskirat singh

Reputation: 1

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

Upvotes: 0

Grundlefleck
Grundlefleck

Reputation: 129287

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?

Upvotes: 3

Henrik Heimbuerger
Henrik Heimbuerger

Reputation: 10203

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.

Upvotes: 10

Vihung
Vihung

Reputation: 13397

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

Upvotes: 5

Cruachan
Cruachan

Reputation: 15981

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

Upvotes: 0

Keith
Keith

Reputation: 155702

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;

Upvotes: 5

ripper234
ripper234

Reputation: 230068

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

Upvotes: 0

jpinto3912
jpinto3912

Reputation: 1465

  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)

Upvotes: 0

Allan Bruce
Allan Bruce

Reputation:

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;

Upvotes: 4

Vinko Vrsalovic
Vinko Vrsalovic

Reputation: 340341

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.

Upvotes: 11

David Pierre
David Pierre

Reputation: 9545

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

Upvotes: 20

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391446

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

Upvotes: 3

Greg Hewgill
Greg Hewgill

Reputation: 993461

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

Upvotes: 6

m_pGladiator
m_pGladiator

Reputation: 8620

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.

Upvotes: 0

Michel
Michel

Reputation: 2472

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.

Upvotes: 22

Ed Guiness
Ed Guiness

Reputation: 35267

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

Upvotes: 5

Related Questions