DEV Community

Discussion on: What are your debugging tips?

Collapse
 
crowdozer profile image
crowdozer • Edited

My main two tips:

Do less debugging by designing modularly.

Functions shouldn't be doing 10 different complex things, break each complex task into its own function and then compose them together.

Instead of:

function doesSomething() {
    // ...
    // doing stuff..
    // ...
    const date = new Date()
    const dayOfWeek = date.getDay()
    const isTodayEvenDay = dayOfWeek % 2 == 0
    // ...
    // doing stuff..
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Consider doing this:

function isTodayEvenDay() {
    const date = new Date()
    const dayOfWeek = date.getDay()
    return dayOfWeek % 2 == 0
}

function doesSomething() {
    // ...
    // doing stuff..
    // ...
    const isEvenDay = isTodayEvenDay()
    // ...
    // doing stuff..
    // ...
}
Enter fullscreen mode Exit fullscreen mode

This is a trivial example, but it's a mountain of loosely related "trivial" things that end up creating hard to debug (and difficult to test) nightmares.

We're all guilty of littering this kind of "trivial supporting logic" in the middle of our business logic. Maybe it's because you were just rapidly prototyping, or maybe someone decided it was a "trivial" amount of complexity so they left it. Then someone else added another "trivial" amount of complexity and... it turns into a lot of mental overhead required to develop and debug.

Reduce complexity. Reduce mental overhead.

Walk through it step by step.

I've seen a lot of people who start working on something complicated, and when it doesn't work, they just lock up. They don't know where to start. Why not start at the start? Or the end. It doesn't matter. Just pick somewhere and look at what's being passed around. Function arguments, return values, etc. Does the first step work correctly? Does the second step work correctly? Why is that value not what you expect? Where did it come from?