Another naming problem reasoning

So this time I was thinking about names for boolean methods.

It started with this example that I saw in our project:

1
2
3
if ($this->simpleProductWasSaved($product)) {
// some actions
}

I assumed that it checks whether the given simple product was saved or not.
But I was wrong. Here’s this method:

1
2
3
4
private function simpleProductWasSaved(ProductInterface $product): bool
{
return 'simple' === $product->getTypeId();
}

While looking as a good descriptive method name it was misleading the developer (me) in his understanding of what the program does.

The author of this code was asking:

Is it a simple product that was saved?

Instead the function asnwered to a different question:

Is this product simple?

Considering that the method doesn’t have a clue about the saving, it has to be called just productIsSimple.

You may notice that I don’t promote calling boolean functions following the pattern “isSomething” or “hasSomething”. Which might seem reasonable at the first glance saying they are answering some question. But I don’t find it so.

The most frequent usage of such methods is inside an if construct:

1
2
3
if (isProductSaleable($product)) {
// sale it
}

This is just uncomfortable to read, it doesn’t sound like a sentense.
And it conflicts with a statement-like expressions with comparison operators that are more than often used in ifs.

1
2
3
4
//  |        question         |    |       statement       |
if (isProductSaleable($product) && $product->getPrice() > 50) {
// sale it
}

You can extract the value into a variable. But I bet you will call it in a statement-like form:

1
2
3
4
$productIsSaleable = isProductSaleable($product);
if ($productIsSaleable) {
// sale it
}

Which makes sense because it’s a statement which is either true or false. But what’s the reason of having a function name that is not always comfortable to use?

Some say that the name starting with “is” or “has” tells about the boolean nature of the function. Mmm. Exactly the same as the name in a form of a statement .

(I don’t consider naming a variable “$isProductSaleable”)

So there’s just no reason to name a function in a form of a question.

Ok, summing up.

  1. Name boolean functions in a form of a statement, not question.
  2. Don’t put irrelevant information in the names you give.

P. S.

Ah, yes, but that’s ok for class methods to start with “is” or “has” when they say something about the subject:

1
$product->isSimple();

This is completely ok, because together with the subjects name it forms a statement.

So these two can leave together happily:

1
2
$product->isSimple();
$product->childrenAreInStock();