Code smells

Definition

A code smell is a surface indication that usually corresponds to a deeper problem in the system. In computer programming, a code smell is any characteristic in the source code of a program that possibly indicates a deeper problem.

The quick definition above contains a couple of subtle points. Firstly a smell is by definition something that's quick to spot - or sniffable. A long method is a good example of this.

The second is that smells don't always indicate a problem. Some long methods are just fine. You have to look deeper to see if there is an underlying problem there - smells aren't inherently bad on their own - they are often an indicator of a problem rather than the problem themselves.

The best smells are something that's easy to spot and most of the time lead you to really interesting problems. Data classes (classes with all data and no behavior) are good examples of this. You look at them and ask yourself what behavior should be in this class. Then you start refactoring to move that behavior in there. Often simple questions and initial refactorings can be the vital step in turning anemic objects into something that really has class.

One of the nice things about smells is that it's easy for inexperienced people to spot them, even if they don't know enough to evaluate if there's a real problem or to correct them. I've heard of lead developers who will pick a "smell of the week" and ask people to look for the smell and bring it up with the senior members of the team. Doing it one smell at a time is a good way of gradually teaching people on the team to be better programmers.

Code smells in JS

  • Too Many Indentation Levels (nested ifs)

  • Long functions

  • Too many parameters in functions

  • Code That Is Too Complex

  • Copy Pasted code

  • Wrong Use of Equality

  • Comments / Dead code

Code smells in React

  • Too many props - Passing too many props into a single component may be a sign that the component should be split up.

  • Incompatible props - Avoid passing props that are incompatible with each other.

  • Copying props into state - Don't stop the data flow by copying props into state.

  • Returning JSX from functions - Don't return JSX from functions inside a component.

  • Multiple booleans for state - Avoid using multiple booleans to represent a components state.

  • Too many useState - Avoid using too many useState hooks in the same component.

  • Large useEffect - Avoid large useEffects that do multiple things. They make your code error-prone and harder to reason about.

Last updated

Was this helpful?