DEV Community

Discussion on: I did it again.

Collapse
 
joelnet profile image
JavaScript Joel

Tip to prevent this from happening in the future: Extract your if logic into its own function.

Instead of:

if (num % 2 === 0) {}

Write:

const isEven = num => num % 2 === 0

if (isEven(num)) {}

This has the additional benefits of making your logic reusable and also making your if statements more readable.

Cheers!

Collapse
 
chrisvasqm profile image
Christian Vasquez • Edited

I really like doing this, but sometimes, when looking at the code really quick, in those languages that use the ! operator, I've found myself doing functions like isNotEmpty() so that I don't overlook the ! by mistake.

Kotlin's standard library has methods like isNotBlank() and isNotEmpty() as part of the String class that showcase this.

Collapse
 
joelnet profile image
JavaScript Joel • Edited

Ramda has a function called complement that can help you build these functions.

import complement from 'ramda/src/complement'

const isEven = num => num % 2 === 0
const isNotEven = complement(isEven)
Collapse
 
kspeakman profile image
Kasey Speakman • Edited

Believe it or not, I did exactly that and still managed to miss the not the first time around.

    let hasToken nextToken =
        not (System.String.IsNullOrWhiteSpace nextToken)
Collapse
 
joelnet profile image
JavaScript Joel

Haha awesome! We have all been there.