Writing good, useful, information 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 in size. 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.
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 references to line numbers in the explanatory text.