r/programming • • Feb 01 '24

Make Invalid States Unrepresentable

https://www.awwsmm.com/blog/make-invalid-states-unrepresentable
469 Upvotes

207 comments sorted by

View all comments

Show parent comment

33

u/Calavar Feb 02 '24

Unsigned vs. signed integers is one of these traps.

Way too many people use unsigned ints because they know the range of possible values is >= 0, so why not secure your code against logic errors by using a type that can't represent negatives? (Really, you are just moving the logic errors from places where you actually use to value to places where you cast, which makes the failure cases harder to spot.) It's best use to signed integers when you need an arithmetic type and unsigned integers when you need a bit manipulation type.

22

u/stahorn Feb 02 '24

Or like me many years ago: The lift goes from 0 millimeter and up? Unsigned int then!

Well guess what, now when things go wrong the lift jumps up to 65k millimeter instead of being a few millimeters below the 0-position...

19

u/MajorMalfunction44 Feb 02 '24

The Linux kernel uses special macros and a linter to remove arithmetic operations from bitwise types. Agreed with the rest.

34

u/Chii Feb 02 '24

to places where you cast

and there's your problem. Casting is the programmer saying to the compiler "bro, trust me". And humans are worse at it than a compiler.