Lambda expressions and anonymous delegates are 2 examples where "scope" kind of alters meaning.
You can have a method finish, but your lambda expression code can still be running. They're nice, terse ways to express functionality, but they come from functional programming and look somewhat odd in the context of OO programming, and are counter-intuitive when you look at them the first time.
I'm sure there are other reasons for object lifetime not being entirely determined by scope, but that's one look at "scope".
I fully agree, those things do change matters. My particular rant is towards the following C# pattern:
public bool SomethingSomething(string filename)
SomeClass sc = new SomeClass();
// or ...
SomeClass sc2 = obtainClassForFile(filename);
// Do stuff
// The end.
Nobody ever frees sc nor sc2. Should I have used using()
on this so Dispose() gets called automatically? Maybe. Or maybe not. This pattern works just fine for temporary 'local' types like arrays and the sort.
Woop de wooping wah wah, the GC helps me out by taking the worry of free()ing things away. But now nobody knows WHEN it happens exactly. And there is the pain of garbage collectors running and slowing down your app as a result unless they are very well optimized. Most of the time, it makes no difference.
But it messes big time with our ability, as programmers, to recognise bad situations. I am a big fan of Joel Spolsky's Making Code Look Wrong
article, even though I fail to use those techniques properly half the time as I code too many little things where it does not matter rather than big systems with different sorts of data where such consistency does shine. It explains very well how for code to be maintainable and understandable after you have written it, recognisable patterns are ideal.
In the case of local variables I gave above, you cannot ever be certain you used it properly, unless you decide to throw a using()
statement around every temporary object you create (and that will lead to code that is overly verbose which has its own issues). The simpler code I wrote above cannot ever tell you 'I did this right
', but it can only say 'it looks fine to me
You want the code to say 'Damn, this looks totally wrong!
' and get down to fixing it. You do not
want code that says 'It might be wrong, but it might not be.
', since you either end up ignoring the pattern, or you fruitlessly debug tons of correct code - neither of which is healthy to your sanity in the short term or the long term.
Sorry, I rant again. But I'm a bit more awake right now than I was last time I posted.