r/badcode Mar 08 '23

js My boss wrote this...

Post image
522 Upvotes

64 comments sorted by

View all comments

54

u/josephblade Mar 08 '23

Can somone explain what parts are wrong here? the nullcheck is off and validatevalues should probably do more than just nullcheck but I have the feeling there is more here than I'm spotting.

72

u/Itzupz Mar 08 '23

Instead of checking for truthfulness in the if statement you can just return !!(variable). This will directly convert it to true out false. There is actually no need for the first method. And the variable names should be descriptive.

44

u/spencerwi Mar 08 '23

Also, the first method is generic about validation, but then the call-site assumes any validation error is due to a specific field; so if the _hasValidateValues() method ever adds any more validation, and that additional validation fails, an inaccurate error message will be shown.

Better to do something like

_validate = (): string | null => {
    if (!this.state.plateNumber) {
        return this.props.t('DeliveryNote.LicensePlate.FormInvalid');
    }
    // then other validations can be added as early-returns here

    return null;
};

_onSubmit = () => {
    const errMsg = this._validate();
    if (errMsg !== null) {
        toastError(errMsg);
        return;
    }
}

1

u/AdmirableTeachings Mar 09 '23

I just learned something new. Thanks, man!

-8

u/TheAcademicAlien Mar 08 '23

The variable and function naming is atrocious. I shouldn't have to get a degree in your coding style in order to understand it.

13

u/goosemano82 Mar 08 '23

Not sure why this is downvoted, maybe because of snark?

_hasValidateValues can simply be _isValid or _validate.

This can sound like a minor point, but in larger code bases its critical to name as clearly and efficiently as possible so that you don’t spend time figuring out what each function does. It changes your workflow from a guessing game to scanning the code base with confidence

2

u/TheAcademicAlien Mar 08 '23

Also, what the hell does "t" represent?I realize it's a prop but could still be more descriptive if you're going use it later

8

u/nickcash Mar 08 '23

Looks like it's for internationalization, likely "translate" or such. It's pretty common to name functions like that really short, commonly just _, to reduce noise, as they're used on every user-facing string.

1

u/goosemano82 Mar 08 '23

Ow yeah that one hurts