cover-img

Code Smell 78 - Callback Hell

Processing an algorithm as a sequence of nested callbacks is not clever.

25 June, 2023

0

0

0

Processing an algorithm as a sequence of nested callbacks is not clever.

TL;DR: Don't process calls in a callback way. Write a sequence.

Problems

  • Readability
  • Hard to debug.
  • Complexity

Solutions

  1. Change callbacks to sequence calls.
  2. Extract repeated Code
  3. Refactor.

Sample Code

Wrong

var fs = require('fs');

var fileWithData = '/hello.world';
fs.readFile(fileWithData, 'utf8', function(err, txt) {
if (err) return console.log(err);

txt = txt + '\n' + 'Add Data!';
fs.writeFile(fileWithData, txt, function(err) {
if(err) return console.log(err);
console.log('Information added');
});
});

Right

var fs = require('fs');

function logTextWasAdded(err) {
if(err) return console.log(err);
console.log('Information added');
};

function addData(error, actualText) {
if (error) return console.log(error);

actualText = actualText + '\n' + 'Add data';
fs.writeFile(fileWithData, actualText, logTextWasAdded);
}

var fileWithData = 'hello.world';
fs.readFile(fileWithData, 'utf8', addData);

Detection

This problem shines at the naked eye. Many linters can detect this complexity and warn us.

Tags

  • Readability
  • Complexity

Conclusion

Callback Hell is a very common problem in programming languages with futures or promises.

Callbacks are added in an incremental way. There's no much mess at the beginning.

Complexity without refactoring makes them hard to read and debug.

Relations

Code Smell 06 - Too Clever Programmer

Code Smell 102 - Arrow Code


There are two ways to write code: write code so simple there are obviously no bugs in it, or write code so complex that there are no obvious bugs in it.

Tony Hoare

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code

0

0

0

Maxi Contieri

Buenos Aires, Argentina

🎓Learn something new every day.📆 💻CS software engineer 👷coding👨🏽‍🏫teaching ✍🏾writing 🎨Software Design 🏢SOLID 🌉TDD 👴Legacy 💩Code Smells

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.