3.2.10 - Local variables and modular design (C#)
Keep a subroutine's temporary data local and connect program modules through clear interfaces. Native C# execution is unavailable here; required written answers remain C#, with an optional Python demonstration.
Lifetime and scope of local variables
A local variable belongs to the subroutine or block in which it is declared, rather than being accessible throughout the program.
static double CalculateCost(int quantity, double unitPrice)
{
double subtotal = quantity * unitPrice;
return subtotal;
}
subtotal is declared inside the method. For ordinary calls, it exists while that call executes and is accessible only within its enclosing block. Code in Main cannot read subtotal directly; the returned value carries the result out. Two separate calls calculate their own subtotal. A previous call's temporary value is not a shared running total.
Local variable
A variable declared within a subroutine or block whose accessibility is limited to that scope, normally with a lifetime limited to that execution.
Local variables reduce accidental interference: another module cannot silently alter this temporary value. They also make a module's behaviour easier to understand because its data is close to the code using it. Avoid relying on hidden shared state when ordinary parameters and return values express the intended interface.
Clear documented interfaces
A module's interface describes how other code supplies its inputs and receives its output without depending on its internal temporary variables.
For CalculateCost, document the parameter order, types, meaning and permitted inputs, plus the returned value:
| Interface item | Contract |
|---|---|
quantity | Integer number of items, zero or greater |
unitPrice | Real price per item in pounds, zero or greater |
| Return | Real total in pounds, quantity multiplied by unit price |
| Local data | subtotal, an internal temporary result |
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account