Blog post

Naming boolean variables

Dattatray Kale

-
August 9, 2019
Programming
Clean Code
Software Design
Software Craftsmanship
Poster vector created by makyzz — www.freepik.com

The boolean variables in codebase should read more like a question that answers either yes or no. If it doesn’t answer in ‘yes’ or ‘no’ format, then please revisit naming.

Below are some of the bad examples which feel like commands and I don’t think they are really answering the question in either yes or no format.

Bad

  • emptyUrl
  • openFile
  • startJob
  • closeConnection
  • logIn

They feel more like verbs/actions/commands. For example emptyUrl. In my opinion, it conveys that it empties an URL. Similarly, openFile seems more like a command that opens a file. Let’s see some of a good example of naming the boolean variables.

Good

  • isUrlEmpty
  • hasFileOpened
  • hasJobStarted
  • isConnectionClosed
  • loggedIn

Are these variables answering in yes/no format?

While naming boolean variables, you could use verbs like is, has, can, was, contains and so on that could be part of a variable name.

More Examples:

  • isAdminUser
  • hasInvalidCharacters
  • canUploadFile
  • wasPackageDamaged
  • containsBadWords
  • containsDamagedItems
  • shouldCreateSession
  • isComponentMount…

Originally published at https://beingcraftsman.com on May 23, 2018.

Related Blog Posts