Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 723
12 revs Avatar asked Sep 29 '16 00:09

12 revs


2 Answers

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 glance 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.
like image 50
Jason C Avatar answered Oct 10 '22 18:10

Jason C


A boolean has two options, but those options are "true" or "false" (or, occasionally, "yes" and "no").

We do not generally represent other variables with two options as booleans.

If you have tyre types (of which there currently so happen to be two), I would suggest enums for this.

As always, there are exceptions. If your tyre types are "tyre with oil on it" and "tyre without oil on it", then you could use a boolean called tyreHasOilOnIt.

Really, it is up to you.

like image 26
Lightness Races in Orbit Avatar answered Oct 10 '22 18:10

Lightness Races in Orbit