Presentation is loading. Please wait.

Presentation is loading. Please wait.

The lifespan of a variable

Similar presentations


Presentation on theme: "The lifespan of a variable"— Presentation transcript:

1 The lifespan of a variable
Scope The lifespan of a variable

2 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

3 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

4 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!!

5 Scope Can use variable in surrounding scope(s)

6 Scope Variables in different scopes can have same name BAD IDEA

7 Scope Problem Might need value from calculated in a narrower scope:

8 Bad Scope Solution Bad idea: do all other work inside if/else
Repeating code is a sign of design failure!!

9 Better Scope Solution Declare variable in scope you want it
Modify it in if/else

10 Design Principle 1 General Principle:
Don't declare things until you need them Use maximally narrow scope Yuck Too much info up front

11 Maximally Narrow Scope
Better Variables appear when needed

12 Design Principle 2 Don't repeat same work in multiple places Yuck
Same work in two places

13 Do Not Repeat Work If it always happens, keep it out of the if Better
Factor our common code to before or after if


Download ppt "The lifespan of a variable"

Similar presentations


Ads by Google