Good examples

Tag places in your private source code as good examples for others

Every time we hired a new engineer we had to show them places in our code where we solved specific problems. Sometimes it was to show how we tested a certain feature, or how we log things, or even how we document modules and functions. Finally, we have arrived at a good solution to showing interesting places in our code. The solution was very simple and seems to work.

We sprinkle // GOOD EXAMPLE <lengthy description of what this code does well> in our private source. For example, one of our unit tests mocked global assertion function using Jasmine spyOn function, and then used an alias to the original function to check that the method under test really threw an exception. It took some time to understand how to test this feature (because this is the failure path), so I thought it was useful to remember this code the next time. So I added a comment above the code

1
2
3
4
5
6
7
8
9
10
11
12
13
// GOOD EXAMPLE spying on methods during testing (mocking)
it('raises error if load fails', function () {
spyOn(window, 'la');
// la(condition, arg1, arg2) will be recorded by the spy
// but the actual window.la will NOT be called.
// http://jasmine.github.io/1.3/introduction.html#section-Spies
// window.la will be restored automatically after this spec finishes
loadResource('invalid url endpoint');
// window.la and window.lazyAss are aliases
// use different alias to window.la to avoid the spy
// and verify the loadResource threw an exception
lazyAss(window.la.mostRecentCall.args[1] === 'failed to load resource');
});

Any engineer can add GOOD EXAMPLE tag. We only ask the engineer to:

  • Search existing examples to see the same general concept has been tagged already. If it has been, pick old or new code to be the new example. Having an upper limit on the number of good examples will also help us keep the quality of the examples higher.
  • Add generous comments (just like above) that explain what is going on. Target a novice programmer or someone new to the code base.

We do not limit the total number of example right now, but probably will once the number of examples passes 25. We plan to do this because when someone searches for examples using grep -irn "good example" . we want only a single terminal screen of results. Even when showing a few extra lines with each search result, we still want just a few screens of code (using command grep -irn -A 5 "good examples" .).

Having these good examples tags in our code helps a lot when onboarding a new engineer. After giving the new guy access to the repo and showing the general layout, we show one or two basic good examples and then let him / her discover and read through other good examples.