
Variable shadowing happens when an instance variable and a local variable have the same name. It's kinda like having two houses that look exactly the same. When you wake up in the morning, you never know which one you're in.
This can cause problems in programming, so it should be avoided unless you've got a really good reason to do it (translated, don't do it). Why talk about it if you should never use it? It's interesting. And if you catch your friend doing it, you can tell him why it's bad.
In the example below, our output will be "blank":
But that's pretty obvious, right? Here's a little more interesting example:
The above example shows why this is a dangerous thing to do.
Why should you care?
I made all of these examples a little obtuse on purpose, but this can be a serious pitfall if you're not careful. This mistake is painfully easy to make, even if you're aware of what it is and how it happens.
No comments:
Post a Comment