Background
Coders when writing code are normally focused on the problem at hand. Like an artist who is totally focused on his imagination and view of things when painting. However, the core difference between art and code is having to debug it later on.
One of the common patterns that can cause difficulty during debugging is calling functions inside function calls as parameters. This includes instantiating objects as arguments.
e.g.
parametersCollection.Append(GroupManager.GetGroupsParamString(new HashSet<string>(AvailableGroups)));
The Problem
Issues with such coding style comes forward in the following ways:
- Interactive debuggers normally do not show return values of the executed function in watch windows.
- Debuggers that allow interactive evaluation of functions will run the function again on each evaluation.
- Re-evaluation has a performance penalty
- Functions are generally non-deterministic due to various factors which may not be under debugger's control, in which case the re-evaluation can result a different value compared to how the function actually failed.
- Apart from a different return value, the re-evaluation may result in different code path being executed altogether.
- Trying to evaluate the constructed object, reference to which, is missing.
The Solution
The solution to the problem is very simple. Hold the values in variables and pass the variables to the functions instead of function calls.
e.g.
var groupNames = new HashSet<string>(AvailableGroups);
var groupsParameters = GroupManager.GetGroupsParamString(groupNames);
parametersCollection.Append(groupsParameters);
With above, you now have access to the new constructed HashSet that you can evaluate, the parameters, and the result of function call can now be evaluated. Plus the code is now easier to read and proper validation can be applied to the variables before the values are passed to the intended function.
No comments:
Post a Comment