Skip to content

Commit f345bb8

Browse files
committed
Update robot use guidance
1 parent 3c54903 commit f345bb8

File tree

3 files changed

+119
-186
lines changed

3 files changed

+119
-186
lines changed

.vscode/settings.json

Lines changed: 0 additions & 6 deletions
This file was deleted.

source/reference/code-blocks.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
.. meta::
22
:robots: noindex, nosnippet
33

4+
.. _code-block-reference:
5+
46
=============
57
Code Examples
68
=============

source/style-guide/code-example-guidelines.txt

Lines changed: 117 additions & 180 deletions
Original file line numberDiff line numberDiff line change
@@ -18,22 +18,22 @@ Code Example Guidelines
1818
irrespective of language. Language-specific style guidelines and coding
1919
standards are in progress.
2020

21-
Code examples demonstrate how to use our products programmatically. Our readers
22-
use these examples to learn, troubleshoot, or even copy and adapt them for
23-
their own needs. Well-crafted and well-maintained code examples improve the
24-
overall readability and quality of our Docs, helping build trust with users and
25-
reduce reported issues.
21+
Code examples demonstrate how to use our products programmatically.
22+
High-quality, well-maintained code improves our docs' usability, builds our
23+
credibility with users, and helps reduce reported issues.
2624

2725
What is a Code Example?
2826
-----------------------
2927

30-
We define a code example specifically as ***any block of code that is set apart
31-
from the surrounding copy in a page***.
28+
A code example is any size block of code set apart from regular text using a
29+
code-block directive. For details on valid directives, see the
30+
:ref:`code-block-reference` reference.
3231

33-
.. TODO Add section BRIEFLY introducing semantic meaning and why it's relevant to code block vs. inline code
34-
35-
Inline Code vs. Code Block
36-
~~~~~~~~~~~~~~~~~~~~~~~~~~
32+
- Use code-block directives for all code examples. Code blocks are visually
33+
distinct, easier to read, and better interpreted by robot users (such as
34+
screen readers, AI models, and crawlers).
35+
- Do not use inline code markup to format code examples in ``monospace``. Use
36+
inline code for short references within text (such as method names).
3737

3838
1. Inline Code
3939
#. Code Block
@@ -66,18 +66,26 @@ Types of Code Examples
6666

6767
.. NOTE related page: `Reference/Code Examples <https://www.mongodb.com/docs/meta/reference/code-blocks/`__
6868

69-
We categorize code examples in our Docs as ***Usage Examples***,
70-
***Snippets***, or ***Sample Applications***. These categories and their
71-
subcategories have specific definitions and serve specific purposes.
69+
Although "code example" and "snippet" are often used interchangeably, this guidance uses "snippet" to mean a context-less block of code.
70+
71+
We categorize code examples into the following types:
7272

73-
.. TODO adopt the Informational vs Actionable paradigm to explain the difference between usage examples and snippets
73+
- :ref:`Usage Examples <code-category-usage-example>`: Standalone code blocks
74+
that show how to perform a task, including the relevant setup and context.
75+
- :ref:`Snippets <code-category-snippet>`: Code that illustrates a specific
76+
concept or detail in the context a larger example, tutorial, or reference page.
77+
- :ref:`Sample Applications <code-category-sample-app>`: Runnable applications
78+
demonstrating broader use cases.
79+
80+
.. _code-category-usage-example:
7481

7582
Usage Examples
7683
~~~~~~~~~~~~~~
7784

78-
Usage examples are self-contained code examples that establish parameters,
79-
perform basic set-up code, and demonstrate how to accomplish a task using our
80-
product.
85+
Usage examples are complete, actionable code blocks that demonstrate how to
86+
accomplish a specific task using MongoDB tools, drivers, or APIs. Usage
87+
examples are self-contained--they include the context needed to understand,
88+
run, and adapt the code in the code block (e.g. variable declarations).
8189

8290
.. code-block:: csharp
8391

@@ -88,20 +96,25 @@ product.
8896
// Create a new client and connect to the server
8997
var client = new MongoClient(connectionUri);
9098

99+
.. _code-category-snippet:
91100

92101
Snippets
93102
````````
94103

95-
We define snippets as ***a specific, atomic piece of code removed from any
96-
surrounding context.***
104+
Snippets are narrowly scoped code blocks that illustrate a specific concept or
105+
detail, typically as part of a broader explanation or tutorial. Unlike usage
106+
examples, they are informational, rather than actionable.
97107

98-
.. PLACEHOLDER snippets taken out of the context of surrounding content don't really serve a purpose or make much sense.
108+
Snippets are intended to support other content, and they rely on the
109+
surrounding text or context to be meaningful. In some cases, a snippet may
110+
contain intentionally incomplete or invalid code for demonstration purposes
111+
(for example, a snippet showing all possible argument options for a command).
99112

100-
.. note::
113+
Snippets fall into one of the following subtypes:
101114

102-
This guidance makes a distinction between the terms "code example" and
103-
"code snippet." These terms are often used interchangeably. However,
104-
"snippet" here has a specific definition as a type of code example.
115+
- **Non-MongoDB command:**: a command-line (CLI) command for any non-MongoDB
116+
tooling (e.g. ``mkdir``, ``cd``, or ``npm``), often used in the context of a
117+
tutorial.
105118

106119
Snippets can fall into one of the following subcategories:
107120

@@ -110,20 +123,39 @@ Snippets can fall into one of the following subcategories:
110123
page. For example, terminal commands like ``mkdir``, ``cd``, ``npm``, etc.
111124

112125
.. code-block:: shell
126+
- **Syntax example**: an example of the syntax or structure for an API method,
127+
an Atlas CLI command, a ``mongosh`` command, or other MongoDB tooling.
113128

114129
dotnet run MyCompany.RAG.csproj
115130

116131
- **Syntax example:** a tightly-scoped code block showing syntax for an API
117132
method, an Atlas CLI command, a ``mongosh`` command, or other MongoDB tooling.
118133

119134
.. code-block:: text
135+
- **Return example**: an example of an object, such as a JSON blob or sample
136+
document, returned after executing a corresponding piece of code. Commonly
137+
included as the output of an ``io-code-block``.
120138

121139
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
122140

123141
- **Return example**: a code block containing a JSON blob, example document, or
124142
other return object type. Use this snippet type to demonstrate what a user might expect from executing a piece of code.
125143

126144
.. code-block:: text
145+
A timeout occurred after 30000ms selecting a server using ...
146+
Client view of cluster state is
147+
{
148+
ClusterId : "1",
149+
State : "Disconnected",
150+
Servers :
151+
[{
152+
ServerId: "{ ClusterId : 1, EndPoint : "localhost:27017" }",
153+
EndPoint: "localhost:27017",
154+
State: "Disconnected"
155+
}]
156+
157+
- **Configuration object example**: an example configuration object,
158+
often represented in YAML or JSON, enumerating parameters and their types.
127159

128160
A timeout occurred after 30000ms selecting a server using ...
129161
Client view of cluster state is
@@ -158,174 +190,79 @@ Snippets can fall into one of the following subcategories:
158190
name: atlas-default-backupschedule
159191
namespace: mongodb-atlas-system
160192

193+
.. _code-category-sample-app:
161194

162195
Sample Applications
163-
```````````````````
196+
~~~~~~~~~~~~~~~~~~~
164197

165-
Sample applications are fully runnable applications that connect more discrete pieces
166-
of code. They may include error handling, framework integrations, or frontend user
167-
interface (UI) elements.
198+
Sample applications are complete, runnable programs that connect multiple
199+
discrete pieces of code. Sample apps may include error handling, framework
200+
integrations, or frontend UI elements.
168201

169202
General Guidelines
170203
------------------
171204

172-
In general, our code examples should be simple enough to understand, complex
173-
enough to do something interesting, and provide value to our audience.
174-
175-
As you're writing code examples, keep the following guidelines in mind:
176-
177-
Treat Code Like Writing
178-
~~~~~~~~~~~~~~~~~~~~~~~
179-
180-
Apply the same writing guidelines in this Style Guide to your code examples,
181-
unless overruled by language-specific coding standards. For
182-
example, be consistent, avoid jargon, check for typos, write for accessibility
183-
and a global audience, etc.
184-
185-
- Write code to be as clean and easy to understand as possible, even if it
186-
isn't the most efficient or clever way to write it.
187-
- Provide examples that address problems our readers are trying to solve. Don't
188-
illustrate obvious or contrived scenarios.
189-
190-
Follow Best Practices
191-
~~~~~~~~~~~~~~~~~~~~~
192-
193-
Our code examples should always follow generally accepted best practices. This
194-
is especially important because readers will copy and use our code examples
195-
outside of our Docs.
196-
197-
- If code should *not* be copyable by users, ensure the ``:copyable:`` option is
198-
``false`` for the code block. To learn more about this markup, see
199-
`Reference/Code Examples
200-
<https://www.mongodb.com/docs/meta/reference/code-blocks/>`__.
201-
- Always follow best practices for security in your code and in any user
202-
recommendations or instructions. For example, never hard code secrets or
203-
credentials in an example.
205+
Our code examples should always follow generally accepted coding and security
206+
best practices, and all other applicable guidelines in this Style Guide that
207+
don't conflict with language-specific standards. Remember that users copy and
208+
use these code examples outside of our docs.
209+
210+
Keep the following in mind as you write code examples:
211+
212+
- Treat code like writing: Keep it simple, readable, and relevant to the task.
213+
- Write code that is easy to understand, even if it isn't the most efficient or
214+
clever.
215+
- Introduce each code block with context.
216+
- List or note any prerequisites or code dependencies, especially in a tutorial.
217+
- Use descriptive names that clearly convey the purpose of the code element
218+
(e.g. variable, function, class) or placeholder.
219+
- If a code is not intended to be directly used or adapted, such as a return
220+
object example snippet, make sure the code block is not copyable. To learn
221+
how to set the copyable option, see :ref:`code-block-reference`.
222+
- Don't write code examples for anti-patterns. If readers should be aware of an
223+
anti-pattern or a commonly made mistake, communicate this clearly in the
224+
surrounding text, an admonition, or an inline code comment.
204225
- If a code example is not production worthy in a significant way, communicate
205-
this to readers clearly.
206-
- Don't write code examples that demonstrate the wrong way to do something. In
207-
the rare instances that justify calling out how *not* to do something (eg, to
208-
caution against a common bad practice or frequently made error), do so in the
209-
page copy, in an admonition, or through inline code comments that can't be
210-
mistaken for part of the code.
211-
212-
Provide Context and Comments
213-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
214-
215-
Try to include enough information to ensure reader comprehension without
216-
stating the obvious or overwhelming with unnecessary details.
217-
218-
- Introduce each code block with a high-level explanation of what the example
219-
does, and why it's useful.
220-
- List specific prerequisites or dependencies.
221-
- Include code comments directly in the code block to explain or call out
222-
important details, such as non-obvious logic or placeholder values that users
223-
need to modify. Don't restate the code.
224-
225-
.. TODO To learn more, see `TBD - Comments <PLACEHOLDER>`__.
226-
227-
Test Every Example
228-
~~~~~~~~~~~~~~~~~~
229-
230-
Non-working or incorrect examples negatively impact our credibility. Testing
231-
user-facing code examples ensures that they do what we say they do and work
232-
as expected. This is especially important for code that you didn't write
233-
yourself, such as an example provided by a SME or stakeholder.
234-
235-
.. TODO update this section and the callout to DevDocs
236-
237-
.. note::
238-
239-
For information or assistance with testing code examples, reach out to the
240-
DevDocs team in the ``#ask-devdocs`` Slack channel or through the
241-
``@DevDocs`` GitHub team tag.
242-
243-
- Writers: Always compile and test your code examples. Your code should pass as
244-
written for the documentation.
245-
- Reviewers: Run all code examples as part of your review.
246-
247-
For tutorials or content with multi-step examples, confirm that the code works
248-
by walking through every step exactly as written:
249-
250-
- If there are any prerequisite steps or additional setup, begin at the assumed
251-
starting point and complete the prerequisites exactly. Confirm that every step is correct, comprehensive, and necessary.
252-
- If you have to make changes or take additional steps to get an example to
253-
work, make sure those details are reflected in the Doc.
226+
this to readers through inline code comments *and* in the surrounding text.
227+
- Never use real customer data or hard code secrets in your code. If you're
228+
unsure how to handle secrets in your code, reach out to the DevDocs team.
229+
- Use inline code comments to explain or call out important details, including:
230+
- Non-obvious logic or intent. Don't restate the code.
231+
- Omitted or truncated code.
232+
- Test every code example to ensure it works as intended:
233+
- When writing or reviewing, run the code as it displays on the page.
234+
- For tutorials or multi-step examples, begin at the starting point and
235+
complete all steps exactly, including any prerequisites or setup. Don't
236+
skip steps or assume they're correct.
237+
- If you have to make changes or take additional steps to get an example to
238+
work, make sure those details are reflected in the doc.
254239

255240
Considerations for Robot Users, LLMs, and Other AI Models
256241
--------------------
257242

258243
.. note::
259244

260-
This guidance uses phrases such as "robots *understand*" or "models *interpret* code" as convenient shorthand when discussing robot users. interpreted to mean that robot users have human-like reasoning capabilities.
261-
262-
Robot users, such as LLMs (large language models), web crawlers, and other AI models, also consume our Docs content. However, robot users don't understand, think, or learn like a human user. They don't "read code" or "get context." Instead, they are predictive engines that pattern-match, tokenize, and respond based on probability and training data.
245+
For any questions or help writing or testing code examples, reach
246+
out to the ``@DevDocs`` team or use the ``#ask-devdocs`` Slack channel.
263247

264-
To write code examples that robot users can understand quickly and interpret accurately, keep the following considerations in mind:
265-
266-
- Code examples are as complete as possible. If there are omissions or truncations in an example, indicate the omissions clearly (for example, a code comment ``// imports omitted for brevity`` at the relevant line).
267-
- Ensure that transitions to code examples are obvious and explicit.
268-
- Never use inline code markup for code examples. Always use a code block directive, preferably as a shared include.
269-
- Use placeholder variables only when necessary, and ensure they are clearly commented or explained. Avoid placeholder variables that are not self-explanatory.
270-
- Do not insert explanations mid-block. Commentary should be before or after the code block, or as inline comments.
271-
272-
273-
274-
- Code examples are self-contained and provide enough information for robot users to understand their purpose without relying on surrounding text or context.
275-
- code examples that provide enough information for robot users to understand their purpose without relying on surrounding text or context.
276-
- Code is consistently formatted and uses syntax-highlighted Markdown fences (eg., java).
277-
- Uses canonical imports, namespaces, and entry points (no unnecessary aliasing).
278-
- Placeholder variables are either avoided or clearly commented/explained.
279-
- Code includes concise, purposeful inline comments explaining intent or function.
280-
- File names and structure follow standard conventions (e.g., main.py, index.js, etc.).
281-
- Code blocks are single-language — no mixing languages inside one fence.
282-
- All code fences are properly closed to avoid truncating downstream content.
283-
284-
285-
Nice-to-Have: Improves Model Understanding and UX
286-
- Function/variable names are descriptive and realistic (connectToMongoDB() vs foo()).
287-
- Includes expected output blocks after commands or API calls when relevant.
288-
- Uses consistent multi-language tab structures for examples (e.g., JS/Python/Java).
289-
- Avoids over-abstraction — keeps just enough context to make examples meaningful.
290-
- Keeps logic explicit, even if it's less clever (avoid nested ternaries, dense one-liners).
291-
- Experimental, deprecated, or unsafe examples are clearly annotated with warnings.
292-
- Avoids mixing config, shell, and code in the same block — separate into clearly labeled sections.
293-
- Examples reflect the latest stable version of the tooling or API unless otherwise stated.
294-
295-
296-
When writing code examples, there are a few considerations to keep in mind for robot users that also consume our Docs content. Unlike human users, robot users cannot interpret meaning or context directly.
297-
298-
299-
300-
.. collapsible::
301-
:heading: Prerequisites
302-
:sub_heading: Complete the previous steps in the tutorial and install dependencies
303-
:expanded:
304-
305-
Body content goes here.
306-
307-
.. AI models and web crawlers--such as LLMs, Googlebot, or machine translation engines--are referred to as robot users. They also consume our Docs content, so it's important to ensure that our Docs content, including code examples, effectively meets the needs of both human and robot users. Many of these considerations apply to code examples the same way they do to the rest of our Docs.
308-
309-
.. For example, the following are applicable to both human and robot users:
310-
311-
.. - Clear, descriptive headings and subheadings make it easier for users to understand the overall structure and purpose of the page and its elements, including code examples.
312-
.. - Enforcing a consistent, standard style and formatting, for page copy and code, ensures that users can parse the content easily and effectively.
313-
314-
.. - Use clear and descriptive variable names, function names, and class names. Avoid using generic or ambiguous names that don't convey the purpose of the code. This helps robot users understand the code's functionality and intent.
315-
316-
.. The considerations specific to robot users are related to how LLMs and other AI models interpret meaning, which is very limited compared to human users can. Robot users can't reliably understand or assume context or intent, extrapolate extract or assume meaning from the surrounding text or context.
317-
318-
319-
320-
.. The following are considerations to help optimize code examples for robot users, especially LLMs:
321-
322-
323-
.. -
324-
325-
.. - Provide context for every code example through introductory text and succinct code comments. See the
326-
.. `Provide Context and Comments <#provide-context-and-comments>`__ section
327-
.. above for more information.
328-
329-
.. - For longer code examples (such as a single function), opt for keeping it as a single code block with explanatory inline comments as needed. Avoid splitting it into smaller blocks interspersed in the page text.
248+
Considerations for LLMs
249+
-----------------------
330250

331-
.. .. TODO Add explanatory image
251+
The robot users (such as LLMs and other AI models) that consume our docs are unable to infer meaning or intent from context.
252+
253+
To ensure that our code examples are robot friendly, keep the following in mind:
254+
255+
- Write code examples that are self-contained and provide enough information
256+
for robot users to understand their purpose without relying on surrounding
257+
text or context.
258+
- Don't split code into multiple pieces.
259+
- Use inline comments to clearly mark any omitted or truncated sections.
260+
- Explain intent, purpose, or expected code behavior through surrounding text *and* inline comments.
261+
- File names, file structure, and code follows idiomatic, canonical patterns
262+
(e.g. ``main()``, ``index.js``, ``connect()``). Avoid unnecessary aliasing or
263+
non-standard structures unless explained clearly.
264+
- Use consistent, descriptive names that indicate purpose. Avoid vague names
265+
like ``foo``, ``x``, or ``doStuff()``.
266+
- Make sure the correct language is specified for every code block.
267+
- Clearly mark placeholders and explain how to replace them through an inline
268+
comment.

0 commit comments

Comments
 (0)