E3SM-Project / E3SM-Project/scream

Change as many bool as possible to enums (where useful)

Open
#1,305 1 comment 0 reactions 0 assignees View on GitHub
code quality infrastructure priority:wishlist
Dominant language
No language data
Stars
79
Forks
54
PR merge metrics
No merged PRs in 30d

Description

Bool's can be cryptic when found at the call place. Take the function
```
void allocate_vector (std::vector& v, const int n, const bool init_to_random);
```
As the name says, if the last input is `true`, we init the entries to random values. Pretty clear. However, this is how the code looks at the call site:
```
std::vector vec;
allocate_vector(vec,10,true);
```
Not so clear anymore. The issue can be overcome by inserting inline comments, such as
```
allocate_vector(vec,10, /* init_to_random = */ true);
```
but I would argue that's a bit clunky. Compare that with
```
enum InitType {
InitDefault,
InitRandom
};
void allocate_vector(std::vector& vec, int n, InitType);
...
std::vector vec;
allocate_vector(vec,10,InitRandom);
```

It gets even better if you use strong enums:
```
enum class InitType {
Default,
Random
};
void allocate_vector(std::vector& vec, int n, InitType);
void allocate_vector_bad(std::vector& vec, int n, bool init_to_random);
...
std::vector v;
allocate_vector (v,10,InitType::Random); // ok, works
allocate_vector (v,InitType::Random,10); // Compiler error, good.
allocate_vector_bad(v,10,true); // ok, works
allocate_vector_bad(v,true,10); // ARGH! This works too!
```
The last example might be silly, but I _did_ run into something similar with a very well developed linear algebra package, where a mistake at the call site ended up passing a pointer to a bool. Had that bool been a strong enum, the compiler would have barked, and the bug caught right away.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.