This is the segment of the show where Apoch picks some random thing and rants about it for a few minutes. Today, we're going to talk about: boolean valued functions.
(By the way, all of this discussion can be applied to any programming language; I'll be using C++ since it's a widely recognizable syntax. Feel free to adjust the lessons of this rant to the language of your choice.)
So let's say we have a complicated operation, called Frobnicate. This operation does something which may fail, and may succeed. We need to encapsulate the Frobnicate operation into a function call.
Let's write a prototype for our new function: bool Frobnicate();
That was easy, right? On to step two!
BZZZT - WRONG. Please turn in your programmer's license and shuffle away in shame. You have failed.
Frobnicate is not a boolean function. But Apoch, you protest, surely it can either succeed (true) or fail (false)! Yeah, but it can also succeed (false) or fail (true) depending on your style.
A boolean function should only be used for a predicate - a function which asks a yes/no question. So if we have a function IsBork, it can be boolean: either we're Bork, or we are not Bork. But Frobnicate does not ask a yes/no question. Therefore we should not use a boolean-valued function.
There are two ways to handle this situation and make Frobnicate correct:
Error Returns
If your code style uses error returns (that is, functions return whether or not they succeed, and possibly return special constants that indicate the result of the function call) then your solution is simple.
You should have, as part of your standard header package (and please tell me you have a standard set of precompiled headers/boilerplate code/etc. for your projects!) a simple enumeration which handles success/fail returns. Instead of returning true/false, return Success or Fail. This is extremely common in C and C++ land; Win32 and DirectX use this style, for instance.
The solution here looks like this: ResultCode Frobnicate();
Exceptions
If your coding style is to use exceptions, Frobnicate should probably not return a value. Either it throws an exception (something is wrong) or it does not (everything is fine).
The solution looks like this: void Frobnicate();
There you go. Now please, stop creating bool functions for success/fail results. Also, please don't bother assigning a return type to the function if all it ever does is return true;.
Thank you. This has been Apoch's Pet Peeve Corner.
Up next: dancing clowns juggling rabid hyenas! Don't go away!