hinterbu hinterbu - 2 months ago 7
C++ Question

Should I use boolean type for non yes/no answer variable?

I was coding with a beginner C++ group and we were creating a 'Car' class. Someone suggested 'tyre type' as a possible variable/attribute to the class as a boolean type. Another person then asked whether booleans should be directly answerable with a yes/no.

I was just wondering the same. How do you best manage a variable this and how do you later specify two options, such as winter/summer, for this variable?

Answer

Well, it depends.

Your goal is to write clear, readable, maintainable, and correct code. It's not so much that bool necessitates a yes vs. no answer as much as it is a question of whether or not using boolean (or any other type for that matter) helps you to meet these goals. If it makes your code clear, it's worth considering. If it makes things confusing, it's not a good idea.

For example, you may only have two types of tires, but consider a couple of things:

  • How do you know you won't add more later? You don't want to shoot yourself in the foot.
  • When writing / reading the code how do you remember that true is "summer" and false is "winter"? Will you have to maintain that info in your head / always look it up somewhere? Will it be easy to make a mistake? Will it confuse a reader who is unfamiliar with your code?

Think about those kinds of things. In your case, while using a boolean will certainly get the job done, I'd say it's a good use for an enum, even if you only have two values right now (or ever). E.g.:

enum TireType { WinterTire, SummerTire };

Now everything falls into place:

  • You can add new types in the future if you'd like, with no major issues.
  • A variable TireType t documents itself, we know just at a glace that t is a tire type.
  • There is much less of a chance of mistake when entering values: It'll be very hard to confuse WinterTire with SummerTire, whereas true and false discard all semantic meaning.