Developer Relations

Developer Advocacy Manual (10): Writing Code Examples


作者:Christian Heilmann
编译:庄七

Code examples are what make your posts and articles relevant to developers. They mean more than dozens of pages of articles about a product, and more importantly–they invite people to play with your product. You might even often find yourself scrolling directly to the first code example when reading a technical article.

Fact: The success of platforms like StackOverflow shows that keeping explanations to a minimum and letting the code speak makes sense. This also has the unfortunate effect that many developers don’t even bother with the “why” of code anymore, but are happy to stick to the “how” and copy and paste code into their own products. I call these people “FullStackOverflow developers.”

Solve Problems with Examples

What I hate most are “hello world” examples that don’t do anything useful. Instead, my goal is to provide code that solves actual problems.

Fact:* “Hello World” code teaches people to write code, but not how to solve problems with it.* Good code examples should answer the question “How does this technology help me solve a problem?” rather than “How do I use this?” The “How do I use this?” question should be answered by documentation. Code examples should excite people about using the product and draw them into the documentation to understand the details.

So instead of starting by reading the documentation yourself, check out what the tool can do and find a problem you’ve always wanted to solve that this technology can help you with. Then solve it with the product and explain everything you did with code as an example. This is also a great way to check if your product documentation is effective. If you get stuck as the developer’s advocate and can’t find effective documentation, that’s good. You have the best example of how you can help the product by writing that missing documentation.

Show Working Examples

The first thing to show in a code example is a working implementation. Nothing is more powerful than being able to click a link or play with some data in a table to see how the thing works. It’s one thing for you to tell readers how it works–it’s much more meaningful for readers to be able to try it themselves and see it working.

Tip: If the code you’re explaining is part of a larger interface, behind a firewall, or requires authentication, you can still show how it works by recording a screen. These have less impact and may be considered “fake,” but they’re better than nothing. Examples should work, but they should also be beautiful and smooth. Many examples are unsatisfactory or actually violate many basic usability principles–don’t give a poor first impression.

Explain the Necessary Environment

You want to avoid getting people excited about your code and then not being able to get it to work in their own environment. You can address this in several ways:

  • Write defensive code: Check for dependencies before trying to access them.

  • Check online and HTTP status: If your code needs to pull data from a web service, say that users need to be online for it to run. For example, I’ve had many complaints that some of my JavaScript examples don’t work offline or without running a local server. Clearly, I didn’t explain that it needs live data, and for security reasons, certain features of JavaScript only work when accessed over HTTPS, not on the file system.

  • List what’s needed: Say what your dependencies are. For example: “Requires Node and NPM” or “Runs in Microsoft Edge 85 and newer.” If third-party dependencies are needed, find a good tutorial for your readers to install them, and link the dependency name to it.

  • Provide a simple test script: Check for correct setup (see test file for GeoMaker for an example).

  • Provide a developer key for the demo: But make it clear to people that to implement your code, they need a key of their own. Provide a link to apply for a key.

You can’t predict everything people might do wrong when executing your code, but these are good ways to prevent frustration. Which brings me to an important part of code examples: allowing copy and paste.

Write Effective Copy-and-Paste Code

Copying and pasting is probably the most common way to learn code. You can write documentation until your fingers bleed, but the biggest use case is that developers will check a code example, copy and paste it, tinker with it until they get stuck, and then start reading the documentation.

Fact:* Writing clean copy-and-paste examples is very important. Any bad coding habits you add to the code will be copied and become part of the actual implementation.* Examples that don’t work for copy and paste are not only useless, but also catastrophic for your reputation and very frustrating for the implementer. Please make sure to cover the following points:

  • Link all resources: Point image, CSS, and script resources to web locations rather than linking them to local or relative locations. People will copy the code and paste it in their local projects rather than downloading dependencies.

  • Provide complete scripts upfront: People will copy and paste large chunks of script and complain that they don’t work without realizing that other parts are missing.

  • Validate and secure your code: Copy-and-paste code needs to be excellent. Make sure your code plays well with other code and doesn’t cause any warnings or errors.

Downloadable Examples

In your examples, providing a zip file of the demo code for download should be one of the first things you do. You can ask readers to download, unzip, and code along with you. This works well in screencasts and video tutorials. In any case, it keeps your article in the reader’s mind because they have something on their hard drive to remind them.

Providing a compressed version of your demo code can be annoying because every change means you have to repackage the demo. Fortunately, hosted code solutions like GitHub do this automatically for you.

Write Clean, Clever Examples

I’ll emphasize again that your code examples should be the cleanest, most clever code you’ve ever written. It’s very tempting to show a quick and dirty solution to get people started and immediately win praise for creating the shortest code. But that’s what programmers do to impress each other, not what developer evangelists do.

You want to show how to write excellent solutions with the product you’re evangelizing, and every shortcut you take will be copied and used as an excuse not to write excellent code in real projects. That’s not our purpose here.

Instead, demo code can evangelize best development practices and show them in context rather than as an academic exercise. Showing a JavaScript that protects scope by using the module pattern and cleverly uses closures allows you to cross-connect with these ideas and perhaps get some developers to make them part of their coding habits.

Build Code Generators

A nice touch to add to a solution is a code generator that allows implementers to add some parameters, click a button, and get the code they want. This is surprisingly powerful.

There’s a danger that some people will never learn the real implementation techniques. On the other hand, these readers would probably not do so anyway. In any case, you’ll get more people looking at the product.

Host Code and Demos

It may be tempting to host your code and demos on a personal server, which I’ve done myself for years. The benefit of this is that you have control over this server. The downside is that it’s up to you to maintain this server. And you want to spend your time evangelizing, not as a server administrator.

Warning: Over the years, I’ve used my server as a playground, and it’s also been painful when I look at its state. Some of my past code ended up being an excellent attack vector, and once an AJAX demo of mine from 2006 ended up having a spam blog installed in a deep folder. It also meant Google blocked my domain and many other issues. Having a server is fine, but it should also be obvious to you and to people looking at your code that it’s a scratch pad. The code there can and will disappear at any time. It makes sense to consider publishing your demos and code examples in a more maintainable and controlled way.

Version Control

I’ve found that the first thing that saves me a lot of trouble is using version control for everything. Git is the common thing, but even putting your product in OneDrive/Dropbox/Box/Google Drive or any folder is a good idea. You will always mess up, and being able to revert to the last modification of a file is great.

It turns out that using Git also means you can save hard drive space because you won’t create Zip files named “test123-safety-still-works” or create folder structures where each folder is a version name and a date. Using a version control system used to be intimidating, but with the advent of Git and hosting solutions like GitHub and Gitlab, things have become simple. Another practical effect of Git is that you have to comment on your commits. This way, you can create a modification history that can be used to describe the code to potential maintainers or people you want to teach.

Also, having an open-source hosting body like a GitHub profile is an excellent way for people to find your code examples and courses, contribute to them, and give you内涵 feedback. Issues reported as problems on such platforms are easier to understand than random feedback via email or social media platforms. Wherever you set up camp, it’s important that you don’t rely on free plans but get a better, serviced presence on the platform. These are not expensive, and you don’t want to end up in a situation where your code is inaccessible because you’ve reached a certain limit or the platform has changed.

Tip: This is an important point. Any platform you choose should be a backup and a way for people to find you. You shouldn’t host things in a place where you can’t get a backup of all your data at any time to move it somewhere else. Our markets are constantly changing, so make sure you don’t depend on a resource that could disappear soon, along with all your work. Fact: Git-based code sharing platforms are designed to be compatible with each other, so this should give you some sense of security. These platforms are also highly optimized for serving and delivering code, just as YouTube and similar services are optimized for media streaming. One of my main pet peeves when telling people about code is that your tutorials and documentation need to have both executable code and readable code. I’ve spent years changing code that works well to make it display correctly on blog platforms and in books. By hosting your examples on such platforms, this isn’t a problem at all.

Auto-Hosting

Code hosting platforms not only allow you to store your code and make it accessible to people. These platforms also have built-in feedback mechanisms where people can take your code, take a copy, and modify it there as they see fit.

For you, there’s also the option to add wikis and documentation. More importantly, most of these platforms not only allow you to host your code but also to execute it. This naturally has some limitations. You can display HTML, CSS, and JavaScript on almost any of these platforms. Server-side executable code is harder to find places to host, but there are some platforms that allow complete applications to be hosted along with the source code.

Most platforms will include some static site generators like Gatsby, Jekyll, or similar. If you’re reading this book online, this is what I use. The text here is written in markdown, and I use GitHub pages and Jekyll to generate the HTML.

Code Sandboxes

In addition to platforms for hosting your code and products, there are code sandbox services available. These services allow you to write a code example and share both the source code and the executability with the world. These platforms are editors and places to see the results, and are highly optimized for this use case. As an added bonus, they also allow you to embed code examples in blog posts and articles.

JSFiddle was one of the first, later took off at JSBin, and Codepen is another big player in this space. They not only allow you to write basic web code but also provide you with precompilers so you can focus on showing people how a certain abstraction works without having to convince them by setting up and customizing abstraction libraries. When I worked on the Mozilla web documentation team, we found that it was a big win for people to try code directly where it was explained.

During training, you might encounter situations where their computers cannot install any software due to company policy. By using these services, you can still run your courses because all attendees need is a browser and a connection.

Live Coding Environments

Many of these platforms also have demo and live modes that allow you to develop with others in real-time, just as you can use Office 365 and Google Docs to collaborate on writing text. Code Sandbox, Glitch, and many others are good at this, and both Codepen and JSBin have also upgraded their feature sets to accommodate this use case.

Live coding environments are great for showing something to potential clients who are considering booking your workshop or talk. They’re also an excellent way to create a simple use case and solve a problem with a team anywhere in the world. Not surprisingly, they’re also often used in job interviews.

Code Showcases

Some of these platforms do a great job of building communities around code examples. For example, Codepen is a treasure trove of examples to add to your talks and explain what technology makes them possible. However, it’s important to give credit to people. You can also participate and build a reputation for yourself by showing cool things there.

Often these examples play with the latest technology and are a great way for you as a developer evangelist to show their value to potential other users. And, after all, they’re fun to play with. I’ve found quite a few interesting people sharing information through showcase sites, and some demos have played a role in making the browsers I work with perform better because they put a certain strain on the rendering engine.

Reprinted with permission from: Developer Relations »


Similar Posts

Content icon
Content