News for hackers. Stuff that matters.
Re:Flags Are a Code Smell (2014) by aranchelk on Saturday May 21, 2022 @08:13PM (#31463553)
> Ok, so far we have three flags which means we have 23 = 8 possible combinations of flags, but do we really have eight separate legal states? No!

It’s a good argument for a custom sum type in place of the booleans.

Re:Flags Are a Code Smell (2014) by gentleman11 on Sunday May 22, 2022 @12:58PM (#31470289)
Could you elaborate?
Re:Flags Are a Code Smell (2014) by aranchelk on Monday May 23, 2022 @11:50PM (#31487777)
Sum types let you define a type with a set of fixed possible values (a.k.a. inhabitants). You can define Boolean as a sum type:

data Boolean = True | False

The pipe character would be read as “or”. Boolean has two inhabitants. True being one, False being another one. 1 + 1

Alternatively, when you have a data structure like the example suggested by the author, it’s a product type with 3 fields, with Booleans inhabiting each (isDynamic, isVisible, and isEnabled), 2 * 2 * 2, 8 inhabitants.

The argued criticism of this encoding is that when isEnabled is false, no valid values exist for isDynamic or isVisible. They have no meaning for a disabled object.

My earlier definition for Boolean looks like an enum in some languages, but sum types can be more powerful if you’re allowed to define inhabitants with different shapes (curly braces denoting a record with named fields, “::” read as “has type”):

data GameObjectStatus = Disabled | EnabledWith {isVisible :: Boolean, isDynamic :: Boolean}

Now instead of having 8 inhabitants, you have 5 (a sum of 1 and 4) and they each have a valid conceptual meaning.

Languages with algebraic data types (sums and products) like Haskell (and IMO even better PureScript) let you easily define types that have only valid states.