Home > Web Front-end > JS Tutorial > Clean code: why boolean flags in function parameters are a code smell

Clean code: why boolean flags in function parameters are a code smell

Mary-Kate Olsen
Release: 2024-12-12 18:56:17
Original
393 people have browsed it

Clean code: why boolean flags in function parameters are a code smell

Boolean flags in function parameters can make your code harder to read and maintain. Let's see why you should avoid them and what you can do instead.

The problem with boolean flags

Using a boolean parameter often means your function does two different things, breaking the Single Responsibility Principle (SRP). Here's a typical example:

This might look simple, but it has several problems:

  1. Unclear function calls: Reading the code, it's hard to know what the boolean means:
  1. Two functions in one: The boolean works like a switch, making the function do different things

  2. Testing gets harder: You need to check both ways the function can work

  3. Hard to add features: If you need a third option later, you might add another boolean, making things worse

A better way to write it

Split the function into two separate ones, each doing one thing:

This gives you:

  1. Clear names: createTempFile("log.txt") tells you exactly what it does

  2. Simple logic: Each function does just one thing

  3. Easy testing: You only need to test one thing per function

  4. Simple to add features: Need something new? Add a new function without changing the old ones

More examples

This idea works in many situations. Here are some cases:

Login system

Email system

To sum up

Boolean flags in function parameters often show that a function tries to do too much. Making separate, focused functions creates code that is:

  • Easy to read
  • Easy to test
  • Easy to fix
  • Easy to change

Next time you want to add a boolean parameter, think about making two functions instead.


Have you tried splitting functions like this in your code? Did it help? Let me know in the comments!

The above is the detailed content of Clean code: why boolean flags in function parameters are a code smell. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template