Naming functions that returns a Boolean

Among the things that are hard in programming, naming a function or variable takes the top place.

In case you are writing a function that returns a Boolean, prefixing the method name using is or can or should is a great idea. Here are some examples.

Dos

  1. isActive

  2. shouldLogin

  3. canLogin

  4. hasAccess

  5. canDelete

  6. hasValidToken

  7. doesTokenExist

Remember to keep the method name + tone positive


Please Don't Do

  1. isNotActive

  2. cannotLogin

  3. hasNoAccess

  4. hasinvalidToken

In fact, There is more to this. The name of the function can be driven by the intent or action or check being done.

  1. Are you checking some State ? Prefix with is --> isActive

  2. Are you checking possibility of an Action ? Prefix with can --> canDelete

  3. Are you enforcing some Condition ? Prefix with should --> shouldLogin

  4. Are you checking for a resource ? Prefix with does --> doesTokenExist

  5. Are you checking is something is `allowed`? Prefix with can --> canDelete

Naming variables is never easy, Keeping these principles in mind could be useful.


Conclusion

If Programming was a "TOUGH" cake, naming variables would be the cherry. It takes a lot of practice and meaningful code contributions to get this right. Keep going and keep trying. Every day is a learning opportunity.


Thank You

If you have reached so far, congratulations. Please feel free to share your thoughts via the comments.


Let's Connect

Feel free to connect with me on LinkedIn and Twitter if you have any questions.

Until Next time!

Did you find this article valuable?

Support Sandeep Gokhale's Blog by becoming a sponsor. Any amount is appreciated!