# Code Smell 235 - Console Side Effects

> TL;DR: Avoid side effects. Always.

# Problems

- Coupling

- Testability

- Reusability

- Function Composition

# Solutions

1. Decouple the code and avoid side-effects

2. Inject the output destination

# Context

Outputting to the console within an internal function generates coupling and side effects

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/c8fcd38572bce8e59bf28ceaede7a055)
```javascript
function drawChristmasTree(height) {
  let tree = '';
  let currentFloor = 1;

  while (currentFloor <= height) { 
      tree += ' '.repeat(height - currentFloor) + '🎄'.repeat(currentFloor) + '\n';
      currentFloor++;
  }

  // This function has side effects
  // You cannot test it
  console.log(tree);
}

drawChristmasTree(7);
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/1c4881a54286a827b8fc037fdd89722c)
```javascript
function createChristmasTree(height) {
  let tree = '';
  let currentFloor = 1;

  while (currentFloor <= height) { 
      tree += ' '.repeat(height - currentFloor) + '🎄'.repeat(currentFloor) + '\n';
      currentFloor++;
  }

  return tree;
}

// The side effects are OUTSIDE the function
console.log(createChristmasTree(7));

// You can also test it 

const createChristmasTree = createChristmasTree(7);

describe('createChristmasTree', () => {
  it('should create a Christmas tree of the specified height', () => {
    const expectedTree = 
      '      🎄\n' +
      '     🎄🎄\n' +
      '    🎄🎄🎄\n' +
      '   🎄🎄🎄🎄\n' +
      '  🎄🎄🎄🎄🎄\n' +
      ' 🎄🎄🎄🎄🎄🎄\n' +
      '🎄🎄🎄🎄🎄🎄🎄\n';

    const result = createChristmasTree(7);
    expect(result).toEqual(expectedTree);
  });

});

```

# Detection

[X] Automatic 

Several linters warn for this usage

# Tags

- Globals

# Conclusion

Instead of logging directly within internal functions, a more modular and flexible approach is to have functions return values or throw exceptions when errors occur. 

The calling code can then decide how to handle and log these results based on the application's logging strategy.

# Relations

%[https://maximilianocontieri.com/code-smell-17-global-functions]

# Disclaimer

Code Smells are my [opinion](https://maximilianocontieri.com/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned).

# Credits

Image generated by Midjourney
  
* * *

> Memory is like an orgasm. It's a lot better if you don't have to fake it.

_Seymour Cray_
 
%[https://maximilianocontieri.com/software-engineering-great-quotes]

* * *

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]
