The Introduce Explaining Var refactoring introduces a local variable, and replaces the selected text (expression) with the variable.
The variable is initialized using the selected text. Commonly used to make complex expressions more readable.
An Example
1 2 3 4 5 |
function Price(Quantity, ItemPrice: Integer): Extended; begin Result := (Quantity * ItemPrice) - (MaxInt(0, (Quantity - 500)) * ItemPrice * 0.05); end; |
This calculates the price of an order by subtracting a discount from the base price.
To make this code more readable we could introduce an explaining variable discount using the refactoring.
To do that, select the discount expression “(MaxInt(0, (Quantity – 500)) * ItemPrice * 0.05)” and invoke
the refactoring.
This will be the result:
1 2 3 4 5 6 7 |
function Price(Quantity, ItemPrice: Integer): Extended; var Discount: Extended; begin Discount := (MaxInt(0, (Quantity - 500)) * ItemPrice * 0.05); Result := (Quantity * ItemPrice) - Discount; end; |