Knot-of-nots: Avoiding negative names for boolean methods

Better practice for naming methods that returns boolean

Thameena S
Level Up Coding

--

The usual convention to name methods that return boolean is to prefix verbs such as ‘is’ or ‘has’ to the predicate as a question, or use the predicate as an assertion. For example, to check if a user is active, you would say user.isActive() or to check if the user exists, you would say user.exists().

But when the intention is to check if the user is not active, I've come across code that is written as user.isNotActive() or user.isInactive(). The problem with having negative method names is that it becomes harder to understand when you try to reuse the same method for the positive use-case.

Consider the following scenario. We need a list of users that does not have a prime subscription. The method that has this logic might be named as user.doesNotHavePrimeSubscription() or user.hasNoPrimeSubscription().

Works well for this use case. However, it is highly likely that we might need to get the list of users that has a prime subscription in the future. To re-use the existing method, the if statement will have to be written in this format:

!user.doesNotHavePrimeSubscription, being a double negative statement, makes it confusing to understand such a simple use-case, especially when it comes to complicated methods. To make your code easily readable, change negative verbs to affirmative ones.

Rather than ending up in a knot of nots, it's always a better practice to construct the method name using the positive form of the verb and prefix
a ‘!’ (not) only for the negative use-case. A very simple convention, if followed, that will help in better code readability and reusability.

--

--