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

推荐订阅源

Martin Fowler
Martin Fowler
L
LINUX DO - 最新话题
P
Proofpoint News Feed
Cyberwarzone
Cyberwarzone
Know Your Adversary
Know Your Adversary
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
Lohrmann on Cybersecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Security Latest
Security Latest
T
The Exploit Database - CXSecurity.com
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy & Cybersecurity Law Blog
K
Kaspersky official blog
The Last Watchdog
The Last Watchdog
Webroot Blog
Webroot Blog
Scott Helme
Scott Helme
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
WordPress大学
WordPress大学
L
LINUX DO - 热门话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Visual Studio Blog
O
OpenAI News
AI
AI
Hacker News: Ask HN
Hacker News: Ask HN
V2EX - 技术
V2EX - 技术
GbyAI
GbyAI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Simon Willison's Weblog
Simon Willison's Weblog
S
Schneier on Security
Spread Privacy
Spread Privacy
Y
Y Combinator Blog
I
InfoQ
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
F
Fortinet All Blogs
C
CERT Recently Published Vulnerability Notes
T
The Blog of Author Tim Ferriss
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
N
News and Events Feed by Topic
Project Zero
Project Zero
小众软件
小众软件
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
B
Blog
G
Google Developers Blog

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
Newspaper Code Structure
2015-05-18 · via Kent C. Dodds Blog

This post has been archived because I don't do this anymore.

Your code should read like a newspaper article. Important stuff at the top, details at the bottom. I have a particular convention for my code that leverages some of the quirks of JavaScript to produce much consumable code. I want my code to be easy to read by people regardless of their editor (or without an editor at all, like on GitHub).

Here's a common way to write code that I see all the time. Pretend that you need to use this module. See how fast you can find out what the api to this module is (and objects from the module):

export const bar = {
	some: 'property',
	someFunction() {
		// with plenty of lines
		// and more stuff
		// because... reasons...
	},
	someOtherFunction() {
		// because we need it
		// it's really important...
	},
	someOtherProperty: true,
	anotherFunction() {
		// forgot about this one...
		// why is it here, instead of at top?
		// who knows... Doesn't affect functionality right?
		// but it might impact readability...
		// especially if it gets long and stuff
	},
	dontForgetMe: '!!!!',
	ohWaitNeedThisToo() {
		// yet another function
		// man, I need a few of these don't I?
		// what other functions does this "bar" thing have?
		// does this file export anything else? I guess I'll have to search around and find out...
	},
}

export function longFunction() {
	// I could really use a doughnut right now...
	// Sometimes functions need to do a lot of things
	// You should keep these functions short
	// Otherwise your code is hard for a reader to consume...
	// and that makes me sad :-(
	// and confused
}

export function meToo() {
	// make sure you scroll around the file
	// so you know EVERYTHING that this module exports
	// Because with this method, discovering that is a little difficult.
	// There's gotta be a better way!
}

export const thereIsABetterWay = true

What's the problem?

I hope that I illustrated the issue in the comments in the code there. The main problem is when I come in to maintain this file or even consume it. I have a hard time knowing what the API into this module is. This just makes reasoning about that code much more difficult. I also personally think that it's harder to read, but that could be just because I'm used to my own method now.

Is this for real?

I used to work on a huge Backbone application (150k+ lines of code). Many of our Backbone.Views looked very much like the bar in this file (really tall, hard to know what functions are available on the view). In fact, one of the worst views in the application was 2000+ lines of code! Now everyone knows that is a bad practice just in general. But even if it had been that long, using my suggested different approach would have really helped maintaining that monster.

A different approach...

Now, see how fast you can determine the api to the rewritten module (some comments different, so read those too):

const bar = getBar()
const thereIsABetterWay = true

export { bar, longFunction, meToo, thereIsABetterWay }

// function declarations
function getBar() {
	// main "export" for the function
	return {
		some: 'property',
		someFunction,
		someOtherFunction,
		someOtherProperty: true,
		anotherFunction,
		dontForgetMe: '!!!!',
		ohWaitNeedThisToo,
	}

	// function declarations
	function someFunction() {
		// with plenty of lines
		// and more stuff
		// but I don't mind anymore, because I only read this if I'm interested in it
	}

	function someOtherFunction() {
		// because we need it
		// it's really important...
	}

	function anotherFunction() {
		// forgot about this one...
		// why is it here, instead of at top?
		// who knows... Doesn't affect functionality right?
		// it doesn't actually make a difference
		// even if it gets long and stuff
	}

	function ohWaitNeedThisToo() {
		// yet another function
		// man, I need a few of these don't I?
		// what other functions does this "bar" thing have?
		// I know just by looking at the top of the enclosing function... It's obvious... Important stuff at top, details at bottom
	}
}

function longFunction() {
	// I could really use a doughnut right now...
	// Sometimes functions need to do a lot of things
	// You should keep these functions short
	// Otherwise your code is hard for a reader to consume...
	// and that makes me sad :-(
	// and confused... But at least I know what the API is and it'll make consuming and maintaining this file much easier
}

function meToo() {
	// Don't need to make sure you scroll around the file
	// so you know EVERYTHING that this module exports
	// Because with this method, discovering the exports is obvious
	// It's just at the top of the file. What I see when I first open it up
}

Why is this better?

Hopefully I explain that well enough in the comments in the code, but you should notice right from the get go at the top of the file that it's much easier to know what the API to this module is. If I'm tasked with maintaining this module or using its API, I know exactly what to expect from this file.

Note, this leverages the "quirk" in JavaScript with function declarations which basically amounts to the function definition and declaration getting hoisted to the top of the closure. This is why you can put function declarations after the return statement.

What about ES6 Classes and/or this?

This kind of breaks down with Classes because they must be structured like this:

export default class Person {
	constructor() {}
	walk() {}
	talk() {}
}

Again those functions can get long and you're pretty much in the same scenario as the first sample of code. This is one of my personal beefs with classes. Lots of people just say that your IDE should help you, but your IDE doesn't help much if you're just looking at the code on GitHub and that's important to me because I'm pretty involved on there and it's also important to me that I don't enforce what editor/IDE people use and that its consumable by anyone.

So what's the solution? I don't know to be honest. I'd like to say that the solution is just to keep your code clean and short, but in my experience, I've found that just doesn't cut it sometimes.

Keep files/functions small

Most of these problems kind of go away if you keep your files and functions small. But sometimes that's hard to do and abstractions can only get you so far. I use this code structure even if the amount of code I have is small.

Closing

Thanks for reading! Catch me on twitter if you have comments / want to discuss :-)