57

Should I always use is as prefix for boolean variables? What about booleans that indicate something in past? Should I write isInitialized or wasInitialized? Should I write for properties IsManyMembers or HasManyMembers?

Is there any best practices? Or I should just write in accordance with English rules?

60

Not really, as booleans are not always used to indicate that an object "is" something.

"has" is an equally valid prefix "was", "can" are also valid in particular circumstances, also, I have seen the suffix "Able" used.

So Object herring:-
 isFish = true
 isCat = false
 hasScales = true
 hasFur = false
 canSwim = true
 wasEgg = true
 eatAble = true

Object moggy:-
 isFish = false
 isCat = true
 hasScales = false
 hasFur = true
 canSwim = false
 wasEgg = false
 eatAble = false

It all depends on what makes the program readable.

| improve this answer | |
  • 39
    I think I would choose canBeEaten or isEdible over eatAble. – kzh Mar 17 '16 at 19:10
  • 4
    @kzh -- isEdible is good! Not so sure about canBeEaten as its something that happens to the object rather than something the object can do. Picky Picky I know :-). – James Anderson Aug 8 '17 at 4:25
  • 1
    What about a flag to indicate whether something is allowed or not? Is "AllowsExtensions" clear? Or would "DoesAllowExtensions" be clearer, even though longer? – Reversed Engineer Feb 8 '18 at 6:42
  • 2
    @kzh: I initially read eatAble as "is able to eat" rather than "is able to be eaten". All in all, it's ambiguous and would indeed be better avoided. – Flater Aug 10 '18 at 8:05
  • 2
    @Flater sure I agree with you. Terse is better for readability. I saw somewhere that including a verb is useful for booleans. "Is", "Are", "Allow", "Has" are all (conjugated) verbs, which makes sense to me, whereas just "Extensions"is ambiguous in meaning. – Reversed Engineer Aug 16 '18 at 10:26
8

I'd go with English rules. I tend to think about the next coder that is going to look at your work being an axe wielding maniac that is going to come after me if the code is hard to understand. When I keep this in mind the best option for my health is to keep the code clean and easy to read, which means the best English and domain language possible.

| improve this answer | |
  • 4
    "if the cod is too hard to understand" sticking with the fish/cat theme of the other answer I see – scottysseus Aug 8 '18 at 15:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.