To me shadowing of existing values like described in:
Shadowing and Nested function
immutable in F#
f# duplicate definition
FSharp for fun and profit comment
seems to be going against the notion of immutability and type safety that makes F# so strong. Shadowing in F# works different than in C#. It just took me quite some time to find out that a bug in my code was due to unintentional shadowing of a name within the same scope. Is there a way to have compiler warnings for shadowing values in VS?
I know that in some cases it can be useful. for example for Checked Aritmetics .
One place I use shadowing is when resolving an optional parameter to a default value if no value was supplied.
member x.Foo(?myFlag: bool) =
let myFlag = defaultArg myFlag false
...
Also F# Interactive, the way it's implemented now, would be pretty much completely non-functional if we didn't have shadowing.
Shadowing has pros and cons. I too have encountered bugs due to fat-fingered shadowing efforts. On the plus side, it can help keep your variable space clean as @JoelMueller pointed out.
Shadowing bugs are fundamentally different than mutable variable bugs. They are of the typo variety. They are much easier to analyze: historical information loss is minimized to lexicographical context versus environmental context. That is, with shadowing, you can always cleanly trace the value of a binding through mental stack unrolling, whereas variable mutations create what are essentially gotos (jump to address).
Practically, shadowing still eliminates whole classes of bugs. You won't encounter any "spooky actions from a distance". Namely, you won't run into issues with variables captured in closures or variables being modified in nested scopes relative to the current scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With