Tech Tip: Using pointers to refactor your code
PRODUCT: 4D | VERSION: 14.0 | PLATFORM: Mac & Win
Published On: January 23, 2014
Code refactoring is the process of restructuring existing computer code without changing its external behavior. Refactoring improves nonfunctional attributes of the software. Advantages include improved code readability and reduced complexity to improve source code maintainability, and create a more expressive internal architecture or object model to improve extensibility.
The bigger a method becomes the more a developer should consider refactoring. 4D pointer are a very powerful too in the enhancement of readability and source code maintainability. Consider the following snippet.
// // ...some lengthy code // CLEAR VARIABLE(Var_01) CLEAR VARIABLE(Var_02) CLEAR VARIABLE(Var_03) CLEAR VARIABLE(Var_04) CLEAR VARIABLE(Var_05) CLEAR VARIABLE(Var_06) CLEAR VARIABLE(Var_07) CLEAR VARIABLE(Var_08) CLEAR VARIABLE(Var_09) CLEAR VARIABLE(Var_10) |
It is a redundant housekeeping task consuming many lines of code and detracting from the readability of the method.
With the use of pointers this can be refactored into one line of code, improving readability and maintainability.
By creating the folloing method...
If (True) If (False) Begin SQL /* Name: CLEAR_VARIABLES Path: CLEAR_VARIABLES Purpose: Apply the command CLEAR VARIABLE to passed vars ${n} - Pointer - Pointer to variables to clear */ End SQL End if C_TEXT($MethodName_T) $MethodName_T:=Current method name //===================== Declare Variables ================================== //method_parameters_declarations C_POINTER(${1}) //-------------------------------------------------------------------------------- //method_wide_constants_declarations //-------------------------------------------------------------------------------- //local_variable_declarations C_LONGINT($Ndx;$Params_L) End if //====================== Initialize and Setup ================================ $Params_L:=Count parameters //======================== Method Actions ================================== For ($Ndx;1;$Params_L) CLEAR VARIABLE(${$Ndx}->) End for |
...that redundant housekeeping code can be reduced to one line as follows.
CLEAR_VARIABLES (->Var_01;->Var_02;->Var_03;->Var_04;->Var_05;->Var_06;->Var_07;->Var_08;->Var_09;->Var_10) |
This is one exampe, but utilities can be written to reduce numerous commands which have the potential for beign called repeatedly, such as UNLOAD RECORD, REDUCE SELECTION, etc. Note, parameters of the same type can optionally be referred to using the syntax ${...}. See the command Count parameters (Example 2) for further explanation.