Writing good, useful, informative code examples is an art that requires balancing competing concerns.
Code examples need to be:
- simple enough to be understandable, but
- complex enough to do something interesting, and preferably useful.
There is one overarching consideration that you need to keep in mind:
Readers will copy and paste the code example into their own code, and may put it into production.
Therefore, you need to make sure that the code example is runnable, but does not do anything that will cause an application to be insecure, grossly inefficient, or bloated. If the code example is not runnable or production-worthy, be sure to include a warning in a code comment and in the explanatory text. This also means that you should provide all of the information necessary to run the example including any dependencies and setup.
Refer to the Code formatting section of the MDC formatting guide.
If you add or remove lines in a code example, make sure that you update any references to line numbers in the explanatory text.