The lifespan of a variable Scope The lifespan of a variable
Scope Not every variable is available everywhere Principle: Avoids: Name collisions (15 things all called x) Needless complexity Principle: Make variables available only where needed
Scope Scope : where a variable is available Scope defined by the block { } a variable is in x available anywhere in this block disappears at line 16
Scope Scope : where a variable is available Scope defined by the block a variable is in y only available in the if statement block disappears at line 12 Line 14 error!!
Scope Can use variable in surrounding scope(s)
Scope Variables in different scopes can have same name BAD IDEA
Scope Problem Might need value from calculated in a narrower scope:
Bad Scope Solution Bad idea: do all other work inside if/else Repeating code is a sign of design failure!!
Better Scope Solution Declare variable in scope you want it Modify it in if/else
Design Principle 1 General Principle: Don't declare things until you need them Use maximally narrow scope Yuck Too much info up front
Maximally Narrow Scope Better Variables appear when needed
Design Principle 2 Don't repeat same work in multiple places Yuck Same work in two places
Do Not Repeat Work If it always happens, keep it out of the if Better Factor our common code to before or after if