Settings

Theme

Ask HN: Why should variable shadowing be allowed?

1 points by JrProgrammer 6 years ago · 1 comment · 1 min read

Reader

Today I came across a term I had not heard of before: variable shadowing.

The general opinion about variable shadowing is that it is frowned upon for code readability and comprehension.

What would be a use case for programming languages to allow variable shadowing?

PaulHoule 6 years ago

In java I like using variable shadowing in constructors, that is, I write something like:

  public SomeObject(String aField) {
    this.aField = aField;
  }
I think this promotes clarity for the user of the code, although you can possibly make the mistake of writing

  aField = aField;
but if you declare aField as final, the compiler will give you an error if you make that mistake.

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection