返回资讯中心
外部精选
软件工程
#开发者实时流

开发者分享个人编程风格指南

来源标题:A Programming Style Guide

一位开发者公开了自己的编程偏好文档,用于个人项目并尝试在不造成干扰的前提下推动团队采纳。该文档仍在完善中,目前侧重记录零散想法,作者称需更好组织才能有效使用。

Hacker News 最新facundo_olano2026/11/26 · 今天30 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

This is a brain dump of my current coding preferences. I try to adhere to these in personal projects and I try to subtly move team projects in this direction (when it's not disruptive).

At the bottom is a section with the source material where I got most of my ideas from, which I quoted and paraphrased liberally to support my specific style choices.

This document is a work in progress, so far focused on capturing anything that comes to mind. It will likely require better organization to be used effectively.

I use LLMs a lot for coding these days, as most devs I know, but still feel a bit sick about crafting elaborate prompts and weird AGENTS.md files, as if I could somehow imbue these tools with personality or good sense. I've occasionally found myself sending Claude to read one of my blog posts before starting a task (e.g. for testing conventions or to provide context about a project), so I thought why not focus on documenting more of my habits and preferences, for a human audience, for my own sake? If it's human-readable enough then surely Claude should be able to handle it.

Why even bother with style if it looks like we won't be writing much code anymore? Maybe we won't, but at least for now we still have to read a lot of it, so I'd rather have LLMs produce it according to my preferences. I also posit that better style makes better design, and better design leads to better software, LLM or not. And, if it does turn out that we won't need to even read the code anymore, then indulge me on this, my own personal farewell to that side of the craft.

You'll notice that much of this document is spent on software design. I think that programming style is a spectrum that goes from trivial formatting choices (tabs vs spaces, max line length, etc) to software design, even architecture. The automatable aspects should be just automated away and need no discussion. It's the bits that spill into design that are worth being opinionated about: how we distribute code across files directly maps to system modularization; how we name things strongly influences how we understand, communicate about, and modify the system; and so on.

More important than any prescriptive opinion is the ability to trace it back to some agreed upon principle. Opinions are made to be changed, and only by going back to common ground can we evolve our understanding and prevent dogmatism.

The right style is the preexisting, agreed-upon style of the project, if there's one. If there isn't, refer to this document.

Code is a liability, not an asset.

Other things being equal (readability, complexity, economic incentives), the less code the better.

The primary concern of the code writer needs to be the experience of future code readers.

Never sacrifice reader understanding for writer convenience [APoSD][grug].

For any piece of code, there should be enough context in the codebase for a reader to answer "what is this?" and "why is it here?".

If these questions are hard to answer it could mean that: the names should be improved, docstrings or comments are missing, the component should be absorbed by another one, or it shouldn't exist at all.

Simplicity is the most important consideration in a design[WiB][APoSD].

A system is simple when its design is easy to understand and change.

Accidental complexity needs to be minimized, essential complexity needs to be managed.

Essential complexity may be removed by redefining the problem.

Worse may be better[WiB][grug].

Modularity is the primary tool to manage complexity.

Modules are fractal: project, file, namespace, class, function can be reasoned about as modules with interface and implementation.

Modules should be deep [APoSD].

Interface complexity costs more than implementation complexity.

Reducing local complexity at the expense of global complexity is usually a bad trade off.

Breaking modules apart frequently increases global complexity by adding more interfaces and separating things that depend on each other.

Shallow and pass-through modules are a red flag.

Locality of Behavior trumps Separation of Concerns [grug]

Things that need to be understood together should be closer together.

Abstractions help with modularity, but each new abstraction (each new "concept") increases cognitive load on code readers [CD].

Project organization

The project codebase is a module, with its top level files (README, Makefile, project.json, etc.) acting as the interface.

The internal directory structure of a project should be deliberate and meaningful.

Assume that a README file will be read from top to bottom by anyone getting familiar with the project.

Pull-requests are also modules: the title and description are the interface, the code diff is the implementation.

File contents should be readable from top to bottom. This means that important (higher level) stuff should come first

Put primary exported things at the top, internal helpers at the bottom.

If a helper is used by one or two functions only, and for some reason shouldn't be inlined into the function, put it next to those functions instead of at the bottom of the file.

When opening a file, I should be able to quickly answer "what is this?" and "why is it here?". This can be achieved in several ways:

Inferred from the containing package and filename: if this is app/routes/employees.py I know these will be API endpoints related to employees, no need for comments.

If there's a single or primary struct or class at the top of the file, its docstring may suffice to provide explain the module's purpose.

Otherwise a top-level docstring should supply those answers.

The ordering of things of equal importance within a file is another opportunity to convey meaning

e.g. implement the create operation before the delete operation.

Module interfaces

Docstrings (i.e. public interface comments)

Docstrings are part of the interface of a module.

Docstrings should not reiterate the rest of the interface but complement it.

Docstrings should not reveal implementation details.

Docstrings are the best means to capture domain knowledge of the project.

When naming functions and methods, consider how they will be called.

Methods should assume the class/instance name as its namespace, i.e. employee.create not employee.create_employee.

Similarly, if the language supports it, functions should preferably assume the module name as its namespace.

Names should be meaningful and chosen deliberately.

Naming should be consistent through the codebase.

Short names are not necessarily bad.

Excessively long names are distracting.

Natural names allow to reason by analogy and synthetic names prevent ambiguity, choose accordingly[EoC].

Module implementations

Code duplication is not necessarily a problem, knowledge duplication probably is.

Don't extract short, single use helper functions[APoSD][CD].

Only extract single use helper functions if they can be understood on their own and by extracting them the readability of the calling function improves.

Use whitespace deliberately, for instance to separate blocks of code within a large function[APoSD].

Comments are not a smell, they are an aid for communication.

Comments should complement the code, not repeat it (they should capture implementer intent, the why, not the what)

TODO and FIXME comments are an extremely valuable tool to capture current understanding and intent.

It's not always convenient to pursue the best implementation, "the right thing", but it's useful and cheap to document what we currently understand a better implementation would be, what we perceive as weaknesses or opportunities for improvement. This helps future maintainers to get the context of previous work, decide if concerns are still valid, and maybe execute the suggested improvements as part of related work.

In environments where FIXME and TODO notes are considered a smell, a compromise can be to file a ticket and include the ticket number in the comment (which shouldn't replace the comment text!).

Constants

The presence of magic numbers and other literal values is not enough reason to externalize constants, especially not globally shared constants.

A constant declaration at the top of the function implementation that uses it may suffice

If it needs to be accessed from multiple places within a module, put it at the top of that module.

A constants module is a red flag, and should only house things that genuinely need to to be used at multiple places in an app and are not expected to change.

Ask yourself if the modules couldn't be rearrange to remove the constant.

Ask yourself it the constant shouldn't be a configurable app setting instead.

Type specifications

Don't sacrifice reader understanding for writer convenience (type linting and autocomplete)

Input and return type specs improve readability and can reduce the need of clarifying docstring.

Awkward twists of inheritance chains and framework internals to satisfy the checker hurt readability and thus are worse than no type specs at all.

Prefer to loosen checker strictness to sprinkling the codebase with checker rule ignores

Tests

Prefer integration tests to unit tests[CD][grug].

There should be one integration test for each meaningful business/domain rule in the project [UTP].

def test_login_no_verified_fails(self, client): "Unverified users cannot log in."

...

def test_login_succeeds(self, client): "Users can log in after verifying their email."

...

def test_login_wrong_password(self, client): "Login fails with an error message when entering a wrong password."

...

Unit tests should be left for pieces of code that need to be exercised in all of its variations, are complicated to setup, or would be too distracting if exercised as integration tests: complex algorithms, state machine transitions, etc.

Code coverage should only be used to highlight detect untested areas, not as a target or indicator of quality[UTP].

Test code shouldn't have conditionals (if). Split into separate tests.

The system needs to be manually tested by a human, ideally in a production-like environment. No amount of automated test is an excuse to skip some form of production verification.

e2e tests are a nice to have in apps are stable and/or there's high risk in broken integrations going unnoticed

Mocks of intermediate layers of the code are a red flag: they make the tests brittle, coupled to implementation details, with low resistance to refactoring, and low protection against regressions[UTP].

Only mock the system's observable behavior, i.e. its inputs and outputs.

Leverage mock libraries for this purpose, e.g. responses for requests, respx for httpx.

i.e. a refactor from requests.request(url, method='GET') to requests.get(url) should not break a test.

if there is no such library, try to test at the lowest possible layer to preserve resistance to refactoring.

Database

Don't mock the database.

Use the same db setup as in the production application.

Start each test with an empty database (unless that becomes unbearably slow).

Prefer to build the test data through the public interface of the app, instead of taking shortcuts.

E.g. in an HTTP API use the API to create the data, don't update the databse directly.

Test helpers

Don't use imported constants and enums in the tests, those are internals. The literals are the system observable behavior, use that.

When the payloads are short, it's better to inline and repeat them in each test for readability.

When payloads are big enough to distract from the purpose of the test, extract them to a helper at the bottom of the file (not the top!).

Helpers should be extracted to a separate module only if they are generic enough to be relevant to multiple test scenarios.

If the helper is needed in a single module, keep it there.

Don't overcomplicate the helper to satisfy multiple testing scenarios; keep separate versions on the corresponding modules.

Craft the helper function interface to i

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →