Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple variables with same name within one method

I like variables named correctly but in some cases it is very hard to do.

So if my object implements IDisposable then I can use:

using (var whatever = new Whatever()) { //... }

But it is rare case, so I found another way to handle it - anonymous block (not sure how it called correctly):

//...
{
    var whatever = new Whatever();
    //...
}
//...
if (condition)
{
    var whatever = new Whatever();
}

Is it a good approach? Are there any pitfalls or widespread belief that it reduces code readability?

like image 484
Vladimirs Avatar asked Jun 04 '13 16:06

Vladimirs


People also ask

Can you have multiple variables with the same name?

Said in simple terms, if multiple variables in a program have the same name, then there are fixed guidelines that the compiler follows as to which variable to pick for the execution.

Can we declare two variables with the same name in different scopes?

February 14, 2021. A name can represent only one entity in each scope. That is why, in the same scope, there cannot be two variables with the same name as this may generate compiler errors. We can declare two variables or member functions that have the same name within the same scope using namespace .

Can a variable and method have the same name?

Yes it's fine, mainly because, syntactically , they're used differently.

Can we use same name in two variables in Java?

"Of course you cannot have int x and long x fields in the same class, just as you cannot have two methods with the same name and parameter list.". A better analogy is that you cannot have a method with the same name and a different type in the same class.


1 Answers

Basically, if the compiler doesn't complain and your code is readable and easy to understand, there's nothing wrong with that.

For example:

foreach (var foo in foos)
{
   var task = new FooTask(foo);
   task.Run();
}
foreach (var bar in bars)
{
   var task = new BarTask(bar);
   task.Run();
}

This is actually (in my opinion) slightly easier to read than

foreach (var foo in foos)
{
   var task1 = new FooTask(foo);
   task1.Run();
}
foreach (var bar in bars)
{
   var task2 = new BarTask(bar);
   task2.Run();
}
like image 62
p.s.w.g Avatar answered Sep 19 '22 03:09

p.s.w.g