Textbooks love this. You read about how in programming, Booleans determine either TRUE versus FALSE and you may observe a bunch of different scenarios in order to help make the concept more clear. Ok, that makes sense, but I’m a big fan of learning that actually does something. So here is a more specific programming example.
Function Error Catching
Programming often requires imagining every possible situation for something and this example is no different. Imagine you are writing a program that makes change. Let’s just pretend the actual brainwork of making the change happens in a function.
So far, everything looks good, but now consider something else:
// What if they didn’t give any money?
The Solution: Boolean Conversion
So far, that works fine, but every time the program runs, it has to pause and think about something. What if there was a sort of, “express lane” for this cash handling? A real life comparison would be when a customer steps up to the cash register with exact change, and really quite honestly – there is no need to even consider the math for that scenario, right? For computers, while they work fast with the simplest of questions – cutting back on those moments where a program is stopping to consider something briefly – is where more complex tasks impact processing times and can and should be minimized.
In the example below, the best solution to handling that “what if” moment is through Boolean conversion. Doing it that way is useful because it is both verbose and the program will run FAST. It will immediately find true and cut out any extra steps. When things work normally as they are expected to behave, it will take the first true part of the Boolean and ignore the rest.
Speaking of Speed…
“Always put the start curly brace at the end of a line, and not a new line.”
For example, at first, you might think these two functions below look the same, but:
The first function not work. But, why not? Syntactically, the parentheses both even close, right?!