Naming boolean variables

The boolean variables in codebase should read more like a question that answers either yes or no.

If it doesn’t answer you 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.

Dirty

  • 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
  • isFileOpened/hasFileOpened
  • isJobStarted/hasJobStarted
  • isConnectionClosed/connectionClosed
  • 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…

Dattatraya Kale

Aspiring agile software craftsman, clean code, polyglot, in love with different programming paradigm. I am on a never-ending journey towards mastery of software.

Leave a Reply