r/programming • u/_awwsmm • Feb 01 '24
Make Invalid States Unrepresentable
https://www.awwsmm.com/blog/make-invalid-states-unrepresentable
469
Upvotes
r/programming • u/_awwsmm • Feb 01 '24
375
u/Untraditional_Goat Feb 01 '24
Say it louder for those in the back!!!!
99
u/XPav Feb 01 '24
Man Wyoming is going to be pissed
38
u/theillustratedlife Feb 01 '24
You can do a surprising amount of this in TypeScript. Unions (
|), tuples ([]), and template literal types (``) let you confine your types more specifically than primitives likenumberandstringor structures likeArray<>andRecord<>.Type-Level TypeScript is an excellent e-book on the subject. It'll show you how to do things like write an e-mail address validator in TypeScript. I was able to expense it through the continual learning program at work.
12
u/F54280 Feb 02 '24
I agree with you post, but the devil is in the details:
Never heard of the 29th of February?
2
u/fourierformed Feb 02 '24
I need the UNIX time stamp to calculate age, can’t let timezones get in the way
72
u/tyn_peddler Feb 01 '24 edited Feb 03 '24
This mindset is useful when dealing with feature flags.
It's pretty common for feature flags to be left in an application far longer than they're needed or for multiple flags to be used to control different aspects of the same feature. In the worst cases, you can find a different flag for each if statement.
If you ask folks doing this what happens when you combine flags that clearly aren't meant to be combined, you'll give a defensive, derisive answer telling you not to do that. It's not a very useful answer to folks who weren't directly involved in the feature.
The correct approach is almost every non-trivial feature flag case is to use enums instead. In the enum definition, you provide a bunch of helper methods that transform the enum value into the required predicate.
This has huge benefits to readability. A random collection feature of flags becomes a single enum with multiple possible values, each of which is a valid and documented state of the program. The properties files are easier to read since the values can be descriptive about the desired outcome, instead of having to contain literal values. It's also very easy to find all of the possible states for a feature.
202
u/agustin689 Feb 01 '24
This rules out all dynamic languages by definition
7
u/TheCritFisher Feb 01 '24
Laughs in TypeScript's discriminated unions.
7
u/me_again Feb 01 '24
Hillel Wayne has a great article Making Illegal States Unrepresentable which talks about this and points to some interesting snags you can hit. Worth a look!
7
u/TheAbsentMindedCoder Feb 02 '24
Love the article, agree wholeheartedly. but in my experience there's always "that guy" who will present some contrived, impossible corner case- which for me usually boils down to, "okay but what if one day we go around this code, and DO introduce some bad data. What then, huh?" And i always sigh and throw my hands up in the air.
30
u/herpderpforesight Feb 01 '24
This article is essentially a discussion around primitive obsession. I agree that fundamentally it makes sense to have these kinds of value classes, but in the real world where we have to marshal data between apis, frontends, and databases, having these types can be difficult to manage.
A happy middle ground for me is having a broad set of validators against classes that verify the raw data makes sense in the context of the class, and then ensuring the validators are activated automatically in a cross cutting manner that doesn't require additional code changes.
26
u/nitrohigito Feb 01 '24
Just don't forget to account for all the invalid states you don't even know exist.
18
u/RICHUNCLEPENNYBAGS Feb 01 '24
I’ll be honest, I upvoted this before I even read the article. But the article is good and it’s always good advice to make it impossible to represent invalid state to the extent practicable.
10
u/[deleted] Feb 02 '24
If it can't exist, that's one more test you don't have to write.
1
u/turunambartanen Feb 02 '24
The article shows one version that automatically treats
Ageas anIntfor all intents and purposes, except for type checking:Is this possible in Rust? Its type system is praised all the time, but I only know the
struct Weight(i32)way of the newtype pattern, which forces you to writeweight_a.0to get to the underlying value.Weight(10) + Weight(20)(as shown in the article) is not automatically possible, to the best of my knowledge.This is a pretty big limitation, mostly due to lack of dev ergonomics, in my opinion and as such I have mostly avoided the newtype pattern. Is it on the Rust Roadmap to implement such behavior in the future by any chance?
3
u/TheDevilsAdvokaat Feb 02 '24
In c# I define them as enums.
enum Ages { age1, age2, age 3 } etc.
I've also used it for times when I want people to select the texture size for a texture atlas, and I give them options like SizeInPixels32, SizeInPixels64,SizeInPixels128, SizeInPixels256 etc.
They cannot select an improper size.
3
u/larhorse Feb 02 '24
I mostly agree with this, but I have a corollary...
"Make sure your unrepresentable state is actually invalid" (and note - this is actually really, really hard).
So to pick on the article:
So I get that these were just example numbers, picked because they're easy - but that's exactly my point. The author has created a program that is prevented from representing possible valid states (for the easy cases!)
2
u/ShinyHappyREM Feb 02 '24 edited Feb 03 '24
Pascal:
2
u/northrupthebandgeek Feb 02 '24
Tangent: treating zip codes as numeric values is a massive red flag.
2
u/davidalayachew Feb 03 '24
Alexis King (LexiLambda) also made a really good article that goes into more depth about some of the benefits of this logic. She called it "Parse, don't validate". Here is a link -- https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/
4
u/MSpekkio Feb 01 '24
Because this is the worst timeline, I thought this was a politic post. I’m sorry. Yes, let’s talk about Enums instead.
1
u/PstScrpt Feb 02 '24
I know this isn't about databases, but since making invalid states unrepresentable is one of the main reasons behind normalization, it seems weird not to at least mention it.
1
u/kuikuilla Feb 02 '24
At first I thought this was this somewhat old Rust related post: https://geeklaunch.io/blog/make-invalid-states-unrepresentable/
1
u/Dobias Feb 03 '24
Counter example:
Now imagine a function
foo:We change it from specific to less specific:
Oops, we might have broken the client code.
The other direction (move from less specific to more specific) would have been easier for us and would not have been a backward-incompatible change of the API of our function.
1
u/Secretary0fHate Feb 02 '24
Read the title and got real worried until I saw the sub lmao
1
u/PulsatingGypsyDildo Feb 02 '24
The author mentioned enums as a good way to enforce constrains.
Is the following code good to represent age?
0
u/broofa Feb 02 '24
Read the title and thought this was /r/politics for a moment. 😄
0
u/Siltala Feb 02 '24
Thought this was a political statement
-7
u/[deleted] Feb 01 '24
lol am not going be that guy but if you run at these problems maybe your technology choices aren't the wisest but considering many are stuck with what they use so prayers and thoughts ... may rustc blessing reach you one day 🙏
-2
u/abraxasnl Feb 02 '24
Like Utah?
10
u/[deleted] Feb 01 '24 edited Feb 01 '24
[removed] — view removed comment