Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you use tense when naming methods of boolean return type?

So, when you are writing a boolean method, do you use tense, like "has" or "was", in your return method naming, or do you solely use "is"?

The following is a Java method I recently wrote, very simply ..

boolean recovered = false;

public boolean wasRecovered()
{
     return recovered;
}

In this case, recovered is a state that may or may not have already occurred at this point in the code, so grammatically "was" makes sense. But does it make the same sense in code, where the "is" naming convention is usually standard?

like image 988
P. Deters Avatar asked Sep 08 '10 15:09

P. Deters


2 Answers

I prefer to use IsFoo(), regardless of tense, simply because it's a well-understood convention that non-native speakers will still generally understand. Non-native speakers of English are a regular consideration in today's global dev't industry.

like image 129
Greg D Avatar answered Sep 21 '22 06:09

Greg D


I use the tense which is appropriate the meaning of the value. To do otherwise essentially creates code which reads one way and behaves another. Lets look at a real world example in the .Net Framework: Thread.IsAlive

This property is presented with the present tense. This has the implication the value refers to the present and makes code like the following read very well

if (thread.IsAlive ) {
  // Code that depends on the thread being alive
  ...

The problem here is that the property does not represent the present state of the object it represents a past state. Once the value is calculated to be true, the thread in question can immediately exit and invalidate the value. Hence the value can only safely be used to identify the past state of the thread and a past tense property is more appropriate. Lets now revisit the sample which reads a bit differently

if ( thread.WasAlive ) {
  // Code that depends on the thread being alive
  ...

They behave the same but one reads very poorly because it in fact represents poor code.

Here's a list of some other offenders

  • File.Exists
  • Directory.Exists
  • DriveInfo.IsReady
  • WeakReference.IsAlive
like image 39
JaredPar Avatar answered Sep 20 '22 06:09

JaredPar