DEV Community

Discussion on: Code Smell 21 - Anonymous Functions Abusers

Collapse
 
redbar0n profile image
Magne • Edited

Given that "Humans read code", as you said, I find the first example wayyy easier to read than the second. The second example has over 2x as many lines and over 3x as many characters... I don't know if introducing classes was the right solution here, as it adds indirection and complexity. To me, it thus seems that Right is Wrong and Wrong is Right.

To modify the first example so you solve your 5 stated problems, you could simply:

  1. Rename sortFunction()bubbleSort().

  2. Inside it (the sort function), rename fncompare, for clarity, so the if sentence reveals the intent: if (compare(arr[j], arr[j+1]))

  3. Name the anonymous function before passing it into the (newly renamed) sort function:

const compare = (a,b) => { return a > b };
sorted = bubbleSort(scores, compare);
Enter fullscreen mode Exit fullscreen mode

I do agree that anonymous functions can and often are abused, though. But mostly because they are often injected everywhere (typically obfuscating param lists), without the developer having taken the the time to name and declare it (which would simplify the params list, and also reveal the function's intent better).

Collapse
 
netch80 profile image
Valentin Nechayev

+100.
Maybe the problem exists (I canʼt say on its real spread), but the example shows quite opposite case.

Collapse
 
mcsee profile image
Maxi Contieri

Why is the opposite?
can you elaborate?

Do you have a better example?

Thread Thread
 
netch80 profile image
Valentin Nechayev

Why is the opposite?

"Wrong" code in your post is, except naming, is definitely better than "right" code. The only aspect to correct is naming, as already said in another comments (and Iʼd doubt whether naming was spoiled unintentionally).

Do you have a better example?

Should I? Itʼs your goal to show the initial thesis by good examples. But, to cast a seed for discussion, a better example would show
1) effect of passing an unknown function through multiple execution levels and possibly stored in a data structure (and reused much later on),
2) consequence of absence of traceable function origin (and, what is important, just function name isn't enough).

Thread Thread
 
mcsee profile image
Maxi Contieri

IMHO "Wrong" code is more cryptic and less declarative

Even it might seem more compact it is programmed like the 50s

On the contrary, "Right" code is higher level, more reusable and more declarative

Thread Thread
 
redbar0n profile image
Magne

I respectfully disagree, and can only refer you to my first comment for my reasoning, in case you overlooked it.