editione1.0.1
Updated August 7, 2023As youβre reading through code, you will need to hold a mental model of the data in the system and how it is manipulated as the business logic is applied. Some code may be easy to follow, but you may find yourself deep in the codebase without any idea what the data looks like when it reaches a certain function. In these situations, itβs sometimes useful to lean on your logging system to print some data to your log files so that you can inspect it.
Add a few log statements with data youβre interested in. This could be certain values of variables or object properties, or it could be an arbitrary text string that will give you some useful information if you see it in your logs. Either way, setting log statements throughout your code is a quick and easy way to get a snapshot of what your data structures look like at a point in time when the code is executing. Sometimes, a well-placed log statement can reveal a bug youβve been tracking down, or it can expose certain things that help you understand what the code is doing.
All programmers rely on logging to gain insight into what their code is doing, so donβt feel like itβs the wrong way to debug your code. Even the most experienced engineers rely on logging when theyβre developing new features or tracking down a hard-to-find bug.
Occasionally, youβll come across code that you wonβt understand no matter how many log statements you add. Wrapping your head around confusing code is frustrating, especially if youβre trying to figure out how some piece of data is being manipulated. While you may be able to figure it out with enough log statements, itβs messy to add them all over your codebase just to piece together whatβs going on. Sometimes a debugger is the better tool for the job.
When you distill a program down to the simplest form, itβs really just taking some inputs, manipulating the data structures, and producing output somewhere. To really get a grasp on how everything works, you need to understand how the data changes as it moves through the system. While itβs helpful to read through code and build a mental model of what the data structure looks like, itβs sometimes easier to visualize the program with a debugger and observe how the data changes as it moves through the system.
If you have a debugger configured, youβll be able to see what the data looks like at each breakpoint you set. As you step through the debugger, focus on the data and how it changes as you step in and out of functions.