3.2.10 - Local variables and modular design (VB.NET)
Keep intermediate values local and connect modules through clear documented interfaces. Native VB.NET answers are written without Run; an optional Python demonstration explores separate local state.
Lifetime and scope of local variables
A local variable belongs to one executing subroutine instead of being shared throughout the program.
Local variable
A variable declared within a subroutine, accessible within its scope and normally existing only while that subroutine executes.
Function AddBonus(ByVal score As Integer) As Integer
Dim result As Integer = score + 2
Return result
End Function
Sub Main()
Dim result As Integer = 99
Dim changed As Integer = AddBonus(6)
Console.WriteLine(changed)
Console.WriteLine(result)
End Sub
The outputs are 8 and 99. The function's local result is distinct from Main's local result, even though the names match. Main receives the number 8 through the return, not direct access to the function's variable. A later call with score 1 creates its own result 3; it does not continue from the previous 8. Ordinary locals are not persistent stored history.
Scope is where a name can be accessed; lifetime is when its storage exists. A local declared inside a narrower VB.NET block, such as an If body, also has that narrower scope. Use local intermediates to prevent other routines from accidentally changing them and to reduce hidden dependencies. A module-level shared variable can be accessed by several routines and may retain a change, so using it where a local suffices makes reasoning and testing harder.
Optional Python demonstration — two calls, separate state. Predict then run. Change the second call from 1 to 10 and check that the outer result 99 still does not change.
Optional Python demonstration: separate local results
{"exercise_id":"aqa8525-vbnet-local-demo","task_version":"1","runtime_profile":"python-console-v1","original_filename":"local_demo.py","file_mode":"fresh","code":"def add_bonus(score):\n result = score + 2\n return result\n\nresult = 99\nprint(add_bonus(6))\nprint(add_bonus(1))\nprint(result)\n","instructions":"Predict then run. Change add_bonus(1) to add_bonus(10) and run again; identify which output changes and why the outer result stays 99."}
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account