03_05 Scope and Lifetime of Variables – Howtoshtab – how to, lifehacks, tips and tricks

We’ve encountered over and over and over again This basic idea about classes and that is, class definitions have two main parts instance variables for data and methods for behavior Whenever we instantiate the new object it gets its own fresh, complete, copy of all the instance variables and whenever we call a method, it responds by activating that corresponding method in its own class So if you think about it, objects really have two jobs they contain data or their own instance variable and they respond to method calls by invoking the code from the class And classes have two jobs as well they provide this template or blueprint for creating the particular type of object and they store the code for the methods so in other words, they get called eventually when we call a method. when we send a message like this to a object So we might think of an object’s instance variables as sort of a common pool of information that any method in the class can access So when we call a method for a particular object that means that that method has access to any of the instance variables for that object So it’s particularly helpful to split our variables into into these two separate categories.

Those are the instance variables that are declared outside the method we usually make them private and any method in the class can access them and local variables which are declared inside a method they don’t get a visibility modifer and you can only access them inside the method when declared this leads naturally to the idea of scope scope of a variable is the region of the program where we can validly use it which means that the scope of a parameter or local variable is really just the method that declares it and the scope of a private instance variable is any method in the class so we can see in this example i’ve really got a bunch of different levels of scope i’ve got this private instance variable iAmPrivate and that’s accessible in either of these two methods clientMethod and helperMethod meanwhile the parameters and the local variables declared in each method clientMethod or helperMethod they are only accessible inside that method the are not accessible from the other method they each have local scope a method’s scope could have a sort of nested scope that means that any variable that we declare inside some compound statement with curly braces we’re gonna say that has block scope and those variables are only available within the code enclosed by those braces if you take a look at this code there are two different levels of scope for instance there’s the variable sum which is declared outside our control structure here Its declared outside the loop.

On the other hand the counter i and the int variable number are both declared inside the loop. So they are only accessible in there. As soon as that loop finishes running Those will dissappear. We say that i and number have block scope. And that makes sense because they’re only needed inside that loop, never need them outside. Sum on the other hand persists. That leads quite nicely to idea of the lifetime of a variable Which is really just our way of saying How long does this variable exist. Local variables and formal parameters in a method they only exist during that single run of the method. So every time you call a method We get a fresh set of those parameters and a fresh set of those variables. Instance variables on the other hand, they’re persistent They last the entire lifetime of an object. So whenever we actually instantiate a new object That’s when it gets a fresh set of the instance variables. And those instance variables are available Every time we call a method.

They’re sort of the object’s memory. Finally when a particular object gets garbage collected Its no longer being used, that too is when Those instance variables will get wiped. Now because local variables and formal parameters Are limited in their scope and their lifetime to a single method, we can use the same name For different local variables in different methods Without actually causing any kind of conflict. You can see here in these two methods clientMethod and helperMethod we name our local variables both iAmLocal No problem. You can actually even use the same name for a local variable and a global variable As we see here. In ScopeDemo, we got a private instance variable called iAmAVariable And we see we’ve got a local version of that In the method someMethod, called iAmAVariable. Here we’d say that the local iAmAVariable shadows the instance variable iAmAVariable. Shadowing is dangerous because It makes it sort of unclear which version We mean.

In this situation, if I were to refer to iAmAVariable without specifying which one I was referring to, it would default to the more local version. The only way to specify that I actually mean the Instance variable iAmAVariable is to use the prefix this as you see here in the method otherMethod. Here I’m setting the instance variable iAmAVariable To have the same value as the local, formal parameter to have the same value as the formal parameter iAmAVariable. I’m saying this.iAmAVariable gets iAmAVariable. This is not really great practice because its not very clear. However, it is legal. And just to be clear, the keyword “this” refers to The particular instance of the class that we’re in. Its sort of an object’s way of referring to itself. Now with these different types of variables It’s important to have a good plan for when to use which type. Big idea is if we need an object to remember a piece of information, We want to store that information, thats when We use an instance variable.

If we want to send information between two methods That’s when we’d use a parameter And if we want temporary, working storage inside a method That’s a local variable. There’s a bunch of ways to screw this up So let’s take a look at a few. Here’s one way things could go wrong. Suppose I use an instance variable as temporary working storage. So imagine the student class. If I want to add an instance variable that keeps track of the sum Well then when I go to the getAverage method, If I start adding each score to sum, Eventually I’ll see that sum doesn’t actually reset on its own when getAverage finishes. So this method is only going to work a single time because its going to keep taking every single test score every time getAverage is called. We never actually reset it. The better way would be to declare a local variable, sum, inside the getAverage class.

That way it gets wiped every time getAverage finishes. It will return the value and next time, it’ll start fresh. I can also accidentally use a local variable if I’m trying to remember some information from an Object. Here’s an example where in the method setName, I accidentally declared a new local variable, name. Whenever in this method if I were to refer to name, it would default to the local version rather than the instance variable. So in the setter, if I’m saying String name = nm, I’m actually losing whatever parameter it was passed to. The setter’s broken and the only way that I can specify that I meant the instance variable name would be to use this. as a prefix. this.name If I try to use this to change the name of the student, that change is going to disappear Third thing to keep in mind is that you might use an instance variable when you could have used a parameter instead If you think, there’s really only two ways methods can communicate with each other They can either share this common pool of resources, this common pool of instance variables Or they can pass messages back and forth between each other using parameters and return values (inputs or outputs) The first good reason that we would prefer parameters and return values to instance variables is that If methods are sharing this pool of instance variables and one of them misuses one of the variables somewhere, just does something wrong, it changes the value unexpectedly which is things go wrong It can be sort of hard to figure out where that’s happened cause you have a bunch of different methods that are all changing the same values In this code example, In Server Class, m1 sets the value of some instance variable x to 0 and then m2, the second method, uses x as the divisor in the main line of code, in y = 10 / x When we run our client class, it’s not totally obvious what the cause of this is And there wold probably be a good way to do this without relying on the instance variables Second good reason is that if we’re working with a bunch of methods in the class, we want to be able to really thoroughly document and understand the relationships between those different methods And so when we’re explicitly defining how they’re gonna interact, we’re gonna-when we’re saying what parameters they take what exactly the return, that means we’re doing a thorough job explaining all of that and we’re sure to have a better understanding It’s best when we explicitly spell out those constrasts Finally, any code that I write relies on a particular object structure, relies on a particularly set of instance variables you can only use in its original context, when it has all of those instances variables.

If you write code that takes parameters instead, that’s easier to port to different contexts Big idea here is that instance variables are powerful and they’re useful features of object-oriented programming but, we want to minimize our use of them we want to make sure that we’re only using them when they’re truly appropriate we want to use them judicously That means only really using them to track the state of an object and using local variables and parameters whenever we can otherwise Before we close up shop, take a look at these questions Make sure you can talk about the lifetime of an instance variable, local variable and a parameter Also talk about what their uses are Talk about what shadowing is and make sure you can give an example of when it happened, what the problem might be and what explicit thing you have to do to counteract the effect of shadowing And take a look at this code segment Make sure you can identify what the instance variables, parameters and local variables are and describe the scope and lifetime of each.

That’s it!.

You may also like