惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
S
Schneier on Security
The Hacker News
The Hacker News
P
Proofpoint News Feed
Spread Privacy
Spread Privacy
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
I
Intezer
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Schneier on Security
Schneier on Security
Security Latest
Security Latest
AWS News Blog
AWS News Blog
B
Blog RSS Feed
Microsoft Security Blog
Microsoft Security Blog
有赞技术团队
有赞技术团队
博客园 - 叶小钗
The Last Watchdog
The Last Watchdog
O
OpenAI News
月光博客
月光博客
Hacker News: Ask HN
Hacker News: Ask HN
阮一峰的网络日志
阮一峰的网络日志
S
Security @ Cisco Blogs
Google Online Security Blog
Google Online Security Blog
云风的 BLOG
云风的 BLOG
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Latest news
Latest news
P
Palo Alto Networks Blog
Last Week in AI
Last Week in AI
M
MIT News - Artificial intelligence
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
Apple Machine Learning Research
Apple Machine Learning Research
U
Unit 42
PCI Perspectives
PCI Perspectives
博客园 - 聂微东
SecWiki News
SecWiki News
宝玉的分享
宝玉的分享
Forbes - Security
Forbes - Security
H
Heimdal Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Troy Hunt's Blog
博客园 - 三生石上(FineUI控件)
Application and Cybersecurity Blog
Application and Cybersecurity Blog
罗磊的独立博客
WordPress大学
WordPress大学
D
Darknet – Hacking Tools, Hacker News & Cyber Security

Kent C. Dodds Blog

Implementing Hybrid Semantic + Lexical Search Simplifying Containers with Cloudflare Sandboxes Migrating to Workspaces and Nx Offloading FFmpeg with Cloudflare Building Semantic Search on my Content Helping YOU ask ME questions with AI How I used Cursor to Migrate Frameworks The Dow's Start on the Covenant Path 2025 in Review The next chapter: EpicAI.pro AI is taking your job How I increased my visibility Launching Epic Web 2023 in Review Stop Being a Junior RSC with Dan Abramov and Joe Savona Live Stream Fixing a Memory Leak in a Production Node.js App 2022 in Review My Car Accident I Migrated from a Postgres Cluster to Distributed SQLite with LiteFS I'm building EpicWeb.dev A review of my time at Remix Remix: The Yang to React's Yin How I help you build better websites Why I Love Remix The State Initializer Pattern How to React ⚛️ Get a catch block error message with TypeScript Building an awesome image loading experience How Remix makes CSS clashes predictable Introducing the new kentcdodds.com How I built a modern website in 2021 How to use React Context effectively Static vs Unit vs Integration vs E2E Testing for Frontend Apps The Testing Trophy and Testing Classifications Array reduce vs chaining vs for loop Don't Solve Problems, Eliminate Them Super Simple Start to Remix Super Simple Start to ESModules in Node.js JavaScript Pass By Value Function Parameters How to write a Constrained Identity Function (CIF) in TypeScript How to optimize your context value How to write a React Component in TypeScript TypeScript Function Syntaxes Listify a JavaScript Array Build vs Buy: Component Libraries edition Using fetch with TypeScript Wrapping React.useState with TypeScript Define function overload types with TypeScript 2020 in Review Business and Engineering alignment Hi, thanks for reaching out to me 👋 useEffect vs useLayoutEffect Super simple start to Firebase functions Super simple start to Netlify functions Super Simple Start to css variables Favor Progress Over Pride in Open Source Testing Implementation Details How getting into Open Source has been awesome for me useState lazy initialization and function updates Use ternaries rather than && in JSX Application State Management with React Use react-error-boundary to handle errors in React JavaScript to Know for React How I structure Express apps What open source project should I contribute to? When I follow TDD AHA Programming 💡 How I Record Educational Videos Should I write a test or fix a bug? Stop mocking fetch Intentional Career Building Improve test error messages of your abstractions Tracing user interactions with React Eliminate an entire category of bugs with a few simple tools Common mistakes with React Testing Library Super Simple Start to React Stop using client-side route redirects The State Reducer Pattern with React Hooks Function forms Replace axios with a simple custom fetch wrapper How to test custom React hooks React Production Performance Monitoring Should I useState or useReducer? Stop using isLoading booleans Make Your Test Fail Make your own DevTools An Argument for Automation Fix the "not wrapped in act(...)" warning Super Simple Start to ESModules in the Browser Implementing a simple state machine library in JavaScript 2010s Decade in Review Why users care about how you write code Why I avoid nesting closures Don't call a React function component Why your team needs TestingJavaScript.com Inversion of Control Understanding React's key prop How to Enable React Concurrent Mode Profile a React App for Performance
Make Impossible States Impossible
Yaron (Ron) Minsky @yminsky · 2018-09-10 · via Kent C. Dodds Blog

This is a phrase I first heard from David Khourshid in his talk at React Rally 2017 Infinitely Better UIs with Finite Automata: "Make impossible states impossible" (super great talk by the way, and xstate is awesome, and David is too). Googling around it looks like it's a pretty popular phrase in the Elm community, though I'm not sure who said it first.

To illustrate what this means, let's checkout at a very simple example:

<Alert>Just FYI</Alert>
<Alert success>It worked!</Alert>
<Alert warning>Head's up</Alert>
<Alert danger>Watch out!</Alert>

Rendered example

You may have used or written a component that has this kind of API. It's nice and clean (in case you're unfamiliar, in JSX, a non-assigned prop like that is the same as assigning it to the value "true", so success is the same as success={true}).

Here's where this kind of API falls over. What should I render with this?

<Alert success warning>
	It worked!
</Alert>

Should it blend the colors? Should I choose one? Which do I choose? Or should we just yell at the developer trying to do this because they obviously don't know what they're doing? (tip: that last one is NOT what you should do).

The idea of making impossible states impossible basically means that situations and questions like these should never come up. It means that you design APIs that make a clear distinction between the possible states of a component. This makes the component easier to maintain and to use.

So what do we do with our simple example? Whelp, all these different props represent is the type of alert that should be rendered. So what if instead of simply accepting the prop itself, we accept a type prop?

<AlertBetter>Just FYI</AlertBetter>
<AlertBetter type="success">It worked!</AlertBetter>
<AlertBetter type="warning">Head's up</AlertBetter>
<AlertBetter type="danger">Watch out!</AlertBetter>

Now it's impossible to have more states than one because there are only three valid values for the type prop (well, four if you count undefined)! It's easier to maintain, easier to explain/understand, and harder to mess up. Everyone wins!

Conclusion

There are various ways to do this effectively and converting a boolean value to an enum is only one such mechanism. It can and does get more complicated, but the concept can seriously simplify your component's and application's state. This is why I recommend you give David's talk a watch (here it is again). And give xstate a solid look as well. There's some good ideas in that! Good luck!

P.S. After publishing this, several people noted that this phrase was the title of a talk from Richard Feldman at Elm Conf. There's also a talk by Patrick Stapfer from ReasonML Munich Meetup. You may also be interested to check out a similar blog post by @stereobooster.

P.S.P.S. Further revelation about the origin of a similar phrase:

@rtfeldman @axiologic @elmlang I did coin the term "make illegal states unrepresentable", but the idea is of course much older. The phrase "Minsky compliant" surely gives me too much credit, but at least it sounds more positive than the concept of the "Minsky moment".

0 16

Bonus:

Here's a part from my section in the babel 7 blog post that didn't make the final cut but I thought you'd enjoy:

Here's a very simple example of a custom macro that swaps lineand column imports with the line or column where it appears in the code:

// line-column.macro
module.exports = createMacro(lineColumnMacro)
function lineColumnMacro({ references, babel }) {
	references.line.forEach((referencePath) => {
		const num = referencePath.node.loc.start.line
		referencePath.replaceWith(babel.types.numberLiteral(num))
	})
	references.column.forEach((referencePath) => {
		const num = referencePath.node.loc.start.column
		referencePath.replaceWith(babel.types.numberLiteral(num))
	})
}

And then this code:

import { line, column } from './line-column.macro'

console.log(`we're at ${line}:${column}`)
console.log(`and now we're at ${line}:${column}`)``

This will be transpiled into:

console.log(`we're at ${3}:${32}`)
console.log(`and now we're at ${4}:${40}`)

And we don't need to change any config to add that custom transform. Writing and using code transforms is a fair amount easier this way. You can't do everything that a full babel plugin can do, but we're only just getting started with this and look forward to what the community will do with this power.

Play around with the above macro example on astexplorer.net. See if you can make it support an import called lineColumn that is replaced with the sum of line and column. Just for fun!