Walking through your code in debug mode is an easily understood practice understood by even the most junior of developers. It is a quick, effective and powerful manner of development. Of course, the less effort required the better. To state the obvious, allowing a developer to walk-through code at runtime, make observations of values are, followed by a quick incremental adjustment of the code. A common problem with this is that code is not always written in a way that it is easily observable. The introduction of various language features has made code much easier write, but much harder to observe.
Taking a step back, reducing the code complexity and the number of things being done in a given line of code can have a tremendous impact on development. The more method calls in a given expression, the harder it is to work with. Nesting a method call inside of a method call will make it harder and more complicated to identify and resolve bugs that may arise. Consider the following code snippet:
This method could be a very difficult line of code to debug. Let’s say that there is an exception thrown in the GetEmail. In order to verify its functionality, GetSender, GetToAddress, and GetMessage will all need to run first. You can put a breakpoint inside of GetEmail, but this requires leaving the current scope increasing the complexity of the debug effort. Then after a bit of tracing it may be discovered that the failure is occurring in GetEmail, but the actual bug is occurring in GetToAddress. This expression is needlessly complicated. Here is a far simpler alternative:
var toAddress = GetToAddress();
var message = GetMessage();
var output = GetEmail(sender, toAddress, message);
This code may be twice as verbose, but five times easier to trace and debug. Each line can be run in tandem. A breakpoint can be placed in before or after any of 4 methods can execute. There is an opportunity to identify the true cause of the defect more quickly. Also note that I prefer a single output variable which makes it very easy to observe my return value.
Similar issues will arise with chaining methods and shorthand (or abbreviated) constructors. Reducing complexity is often just a matter of assigning simple variables and then operating on the results.
Reducing the complexity of code can have a powerful impact of saving you time, budget and headache. Adopting this along with other practices will help your product and reputation.