cover-img

Code Smell 69 - Big Bang (JavaScript Ridiculous Castings)

Don't mix booleans with non-booleans.

13 May, 2023

5

5

0

This handy operator is a trouble maker.

TL;DR: Don't mix booleans with non-booleans.

Problems

  • Not Declarative Code
  • Hard to debug
  • Magic Castings
  • Accidental Complexity

Solutions

  1. Be Explicit
  2. Don't mix Booleans with non-booleans.
  3. Fail Fast
  4. Be Smarter than your compiler.
  5. Stay loyal to the bijection.

The One and Only Software Design Principle

Sample Code

Wrong

!true // returns false
!false // returns true

isActive = true
!isActive // returns false

age = 54
!age // returns false
array = []
!array // returns false
obj = new Object;
!obj // returns false

!!true // returns true
!!false // returns false

!!isActive // returns true
!!age // returns true
!!array // returns true
!!obj // returns true

Right

!true // returns false
!false // returns true

isActive = true
!isActive // returns false

age = 54
!age // should return type mismatch (or 54 factorial!)
array = []
!array // should return type mismatch
obj = new Object;
!obj // should return type mismatch (what is an obejct negated in a real domain?)

!!true // returns true - it is idempotent
!!false // returns false - it is idempotent

!!isActive // returns true - it is idempotent
!!age // nonsense
!!array // nonsense
!!obj // nonsense

Detection

Since this is a "feature" in some languages it would be hard to test. We can set programming policies or choose more strict languages.

We should detect ! !! usages in non-boolean objects and warn our programmers.

Tags

  • Casting
  • Coercion
  • Javascript

Conclusion

Languages like JavaScript divide their whole universe into true or false values. This decision hides errors when dealing with non booleans.

We should be very strict and keep booleans (and their behavior), far away from non booleans.

Relations

Code Smell 24 - Boolean Coercions

Code Smell 06 - Too Clever Programmer

More Info

Programmer Humor

Double Bang

Mozilla

Wat Video

Credits

Photo by Greg Rakozy on Unsplash


It is easier to write an incorrect program than understand a correct one.

Alan J Perlis


Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code

5

5

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.