Variable shadowing happens when a variable declared in a specific scope has the same name as a variable in an outer scope.
This can lead to three main problems:
- Confusion: The same name can refer to different variables in different parts of the scope, making the code hard to read and understand.
- Unintended Behavior: You might accidentally use the wrong variable, leading to hard-to-detect bugs.
- Maintenance Issues: If the inner variable is removed or renamed, the code’s behavior might change unexpectedly because the outer variable is
now being used.
To avoid these problems, rename the shadowing, shadowed, or both variables to accurately represent their purpose with unique and meaningful
names.
Noncompliant code example
The example below shows the typical situation in which shadowing can occur.
SET SERVEROUTPUT ON
DECLARE
foo VARCHAR2(42) := 'foo';
BEGIN
DECLARE
foo VARCHAR2(42) := 'bar'; -- Noncompliant - this variable hides the one above and should be renamed
BEGIN
DBMS_OUTPUT.PUT_LINE(foo); -- Displays "bar", which is confusing
END;
DBMS_OUTPUT.PUT_LINE(foo); -- Displays "foo"
END;
/
Compliant solution
SET SERVEROUTPUT ON
DECLARE
foo VARCHAR2(42) := 'foo';
BEGIN
DECLARE
bar VARCHAR2(42) := 'bar'; -- Compliant
BEGIN
DBMS_OUTPUT.PUT_LINE(bar); -- Displays "bar"
END;
DBMS_OUTPUT.PUT_LINE(foo); -- Displays "foo"
END;
/