Code Smell 247 - Javascript Function Naming

Written by mcsee | Published 2024/04/16
Tech Story Tags: programming | technology | software-development | software-engineering | web-development | javascript | javascript-development | code-smells

TLDRSome names in immature languages break the [bijection] principle. Avoid ambiguous or bad names. Wrap with your functions. Use mature languages. Don't use *replace()* instead of *replaceAll()* in your code. Use *replaceFirst()* if you need to change only the first occurrence.via the TL;DR App

TL;DR: Bad function names will lead you to defects

Problems

Solutions

  1. Avoid ambiguous or bad names
  2. Wrap with your functions
  3. Use mature languages

Context

Some names in immature languages break the bijection principle.

When you use them, you agree on some semantics that are not the actual behavior.

Consequently, you must know accidental implementations to avoid this defect.

Sample Code

Wrong

const pets = '๐Ÿ˜บ๐Ÿถ๐Ÿ˜บ';
const justDogs = pets.replace('๐Ÿ˜บ', '๐Ÿฉ');

const catsArePresent = justDogs.includes('๐Ÿ˜บ');
// returns true

Right

const pets = '๐Ÿ˜บ๐Ÿถ๐Ÿ˜บ';

const justDogs = pets.replaceAll('๐Ÿ˜บ', '๐Ÿฉ');
// Or
const justDogs = pets.replace(/๐Ÿ˜บ/g, '');

const catsArePresent = justDogs.includes('๐Ÿ˜บ');
// returns false

Detection

  • [x]Automatic

You can search and forbid the usage of replace() in your code and define replaceFirst() if you need to change only the first occurrence

Tags

  • Naming

Level

  • [x]Beginner

AI Generation

All generators avoided this problem.

AI Detection

ChatGPT and Copilot use Regular Expressions to solve the problem.

Gemini and Claude failed to spot the mistake.

None of them use replaceAll() (introduced in ES2021)

Conclusion

Using replace() instead of replaceAll() would not fully achieve the intended result of replacing all occurrences.

It would only replace the first occurrence, potentially leading to incorrect behavior if there are multiple occurrences.

Relations

Code Smell 38 - Abstract Names

Code Smell 41 - Regular Expression Abusers

More Info

What exactly is a name - Part II Rehab

Disclaimer

Code Smells are my opinion.

Credits

Photo by Jari Hytรถnen on Unsplash


We must not blame programmers for their bugs. They belong to them only until the code is merged to the repository. After that, all bugs are ours!

Yegor Bugayenko

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code


Written by mcsee | Iโ€™m senior software engineer specialized in declarative designs and S.O.L.I.D. and Agile lover.
Published by HackerNoon on 2024/04/16