Variable Shadowing in Programming Languages

In the programming language, Shade(Shadowing) means a situation in which an inner sphere is declared with an outer sphere. Same name. The identifier (variables, functions, parameters, etc.) leads to the outer layer where the identifier is temporarily " invisible " in the current field.

Core mechanisms

外层作用域:  let x = 10
                ↓
内层作用域:  let x = 20  ← 外层的x被遮蔽了
                ↓
           在内层访问x,得到的是20,而非10

Watch out, cover it up. Not Overwrite. The outer layer variables themselves have not been modified, but are only temporarily “invisible”. Once out of the inner sphere, the outer variable returns to visible.

Typical examples

JavaScript

let name = "全局";

function greet() {
    let name = "局部";  // 遮蔽了外层的name
    console.log(name);   // "局部"
}

greet();
console.log(name);       // "全局",外层完好无损

Python

x = 100

def foo():
    x = 200      # 这里创建了一个新的局部变量x,遮蔽了全局的x
    print(x)     # 200

foo()
print(x)         # 100

Here's the thing to be noted.x = 200, a local variable is created. But if... Just reading. For outer variables, Python is allowed direct access (LEGB rule). If you want both to modify and to quote the outer variable, you need it.globalornonlocal.

Rust.

let x = 5;
let x = x + 1;   // 合法!这里不是修改变量,而是创建了一个同名的新绑定
let x = x * 2;   // 再次遮蔽
println!("{x}"); // 12

Rust even allows the use of different types of values to shield:

let spaces = "   ";      // &str
let spaces = spaces.len(); // usize,同名但不同类型

Java

class Example {
    int value = 10;  // 字段

    void method(int value) {  // 参数遮蔽了字段
        System.out.println(value);      // 传入的参数值
        System.out.println(this.value); // 10,用this突破遮蔽
    }
}

Hide, overwhelm and redefinition

These concepts can be easily confused, and it is clear by comparison:

Concept The scene. Nature
Shading Different fields, same name variables/parameters Internal identifier hides the outer identifier
Overriding Subclass rewrite parent method Run-time multiple, replace parent behaviour
Redefine Repeat declaration within the same field Usually grammatical error (except for part of the C/C++ scene)

Why should we allow the cover?

  1. Avoiding name-name pollution. The inner logic does not concern itself with the name of the outer layer.i、x、tmp.
  2. The ease of type conversion. Like Rust.let s = "text"; let s = s.len();, you can convert the type without changing the name of the variable.
  3. function parameters. Method parameter with field name (this.name = nameIt is common and readable.

Potential trap

The accident led to Bug.

let user = { name: "Alice" };

if (true) {
    let user = null;  // 不小心遮蔽了,后续代码可能误以为外层的user变了
}

"classic trap" in a closed bag (not a strict shade, but relevant)

for (var i = 0; i < 3; i++) {
    setTimeout(() => console.log(i), 100);  // 输出3, 3, 3
}
// 用let替代var后,每次迭代有自己的块级作用域,避免了这个问题

Too long a veil chain leads to confusion.

let a = 1;
{
    let a = 2;
    {
        let a = 3;
        {
            let a = 4;
            // 此时到底是哪个a?需要向上追溯多层,可读性极差
        }
    }
}

Different language attitudes

Languages Attitude to covertness
Rust Encouraged, considered customary
JavaScript/TypeScript Support, block level fields (let/constIt's more common after introduction
Python Supports a function-level mask, but no block-level fields (if/forIA does not create a new field)
C/C++ Supported, but prone to error (e.g.,if (int x = ...) { int x = ...; })
Go Supported, but recommended by the community to be used with caution
Java Support (fields are often masked by parameters) and compilers will warn against unused masked variables

Summary

Shadeing is a natural product of the system of the operational domain, and it is not a bad thing in itself. Good shades can simplify the code, bad shades can hide Bugs.

So the key is to keep the level of the action area clear when it's dark and not too deep; Need to access both internal and external common-name variables and use the mechanisms provided by the language to break through the shade, for examplethis.x、nonlocal、globalThese. Also, the code code of the team can limit "unuseful shades" like ESLint.no-shadowRules.