DEV Community

Discussion on: Use strong types instead of bool parameters

Collapse
 
pgradot profile image
Pierre Gradot

This is discussion we have from time to time with coworkers.

Whenever aceptable, I would use 2 public functions instead of 1.

The issue with a 2-value enum is that there are not really only 2 values:

enum class Accessible {
  Yes,
  No,
};

void searchLocation(Accessible &accessible) {
  if (accessible == Accessible::Yes) {

  } else if (accessible == Accessible::No) {

  } else {
    // what the f....
  }
}
Enter fullscreen mode Exit fullscreen mode

I haven't decided yet how to consider such cases... What do you think?

Collapse
 
sandordargo profile image
Sandor Dargo

I'd do this instead:

enum class Accessible {
  Yes,
  No,
};

void searchLocation(Accessible accessible) {
  switch (accessible) {
    case Accessible::Yes: 
        std::cout << "accessible\n"; 
        break;
    case Accessible::No: 
        std::cout << "not accessible\n"; 
        break;
  }
  throw std::exception{};
}
Enter fullscreen mode Exit fullscreen mode

Now if you add a new enum value, you'll get compile time warning that you forgot to handle the new case.

Check it here!

If I used the default case, I wouldn't get the warning.

I borrow this idea from Matt Godbolt's talk at C++ On Sea 2020.

Collapse
 
pauljlucas profile image
Paul J. Lucas

Replace the ifs with a switch.

Collapse
 
pgradot profile image
Pierre Gradot • Edited

I guess the exception is not where you wanted it to be. Maye in a default label?

Adding -Wswitch force to cover all cases of all enumerations. This has consequences, especially in existing code base. It would be OK for a new project.

For a simple if/else with a single bool parameter, using a switch case would be fine. But there are other cases, more complex, where the solution won't be that easy.

Examples:

void searchLocation(bool accessible) {
    puts(accessible ? "yes it is" : "no it isn't");
}

bool function(bool A, bool B, bool C) {
   return (A and B) or (not B and C) or (not A);
}
Enter fullscreen mode Exit fullscreen mode

I think you get my point: a two-value enum isn't a boolean. It can be nice in public API. It's not always friendly for implementers.

Thread Thread
 
sandordargo profile image
Sandor Dargo

The exception is exactly at the place I wanted it to be. And exactly because of the warnings it would introduce in existing codebases. As such, I can either make it clearer or actually find and fix/document bugs.

I agree that it's not always straightforward.