Tuesday, August 2, 2022

should_methods_be_named_like_this?

tl;dr: all method names that return a True/False setting should begin with the word is

The Problem

The readability of code is very important to me. Unfortunately English is a remarkably complex language. This leads to a lot of variations on how you can ask a True/False question.

Here are a few:

  • am I allowed to write to files
  • are files writable
  • can I write to this file
  • is this file writable
  • should file writes be allowed
  • was the file writable
  • were the files writable
  • will file writes be allowed
  • would the file allow modification

Consistency

The issue with even considering which of these is the better way of expressing this question in English is Consistency.

“A consistent experience is a better experience.” — Mark Eberman

Your API is the UX that programmers experience and a consistent UX is better, even when it's worse. Why? Because it lowers the cognitive load on a user. New things fit into your existing understanding, Things are where you expect them to be so you don't miss them and they are easy to discover. If I want to know what an object can do it is helpful to be able to ask it 3 general questions:

  1. is - What properties are True/False?
  2. get - What other properties can you give me?
  3. set - What properties can I change?

This convention has been decided decades ago. Furthermore, IDEs will often autocomplete in alphabetical order making things discoverable.

The answer and the problem

This means if you have a method that answers a True/False question, the method should begin with the word is.

But English can make this soooo ugly!
Yes
But...
... it doesn't matter :-(

Yes the present singular form of the to-be verb can make for an awkard method name, but consistency is more important.

> isThisMethodNameInTheCorrectForm()   
True

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.