ALL or null with enumerations?

I noticed that I am doing this inconsistently within the framework of one project. In some places I will have an enumeration with the ALL option, and in others I will enumerate as a null type with a null value indicating all (or without a filter).

I noticed this when I had to write something like if (Region != null && Region != Regions.ALL) .

Is there any reason to go anyway?

+7
source share
3 answers

In cases where Enums you need to specify the type "All" or "Null", I usually use the Flag attribute and use the bitwise & and | . This is a much more flexible solution.

Regarding the creation of the NULL type or the presence of one parameter “Everything”, I think if this makes sense to you, then I do not see any problems with it. I just prefer to use flags.

+2
source

Using Regions.All more obvious how important it is to convey meaning. You can “set” this value to null , and the computer will be fine with it. However, readers of your program will need to decrypt this value from how you use the null enumeration value or read your comments. Regions.All , on the other hand, is self-documenting and self-evident.

+7
source

Typically, we use null to mean "unspecified" or "nonexistent" or "not applicable." Thus, in the case of a filter, it makes sense to allow null, because it means "no filtering."

In addition, an enumeration called Regions probably has values ​​such as Northeast , Southeast , Midwest , Southwest and West . Now, please correct me if I am mistaken, but I do not think that in the USA there is some region called "Everything". During my many years of stay there, I heard the weatherman on television talking about the weather in the West, about the weather in the southeast, etc., but never about the weather in some place called "Everything." Therefore, I am inclined to believe that there is no such region. Therefore, including “Everything” in the list of regions, it’s a hack. Suddenly, the Regions enumeration does not apply to regions; instead, it is about regions and / or their filtering. Shifts in meaning of this kind are what you need to know about in programming and, as a rule, avoid.

+2
source

All Articles