Skip to content

Instantly share code, notes, and snippets.

@maslade
Last active April 22, 2018 11:47
Show Gist options
  • Save maslade/6458190194faa80ee77d3833008506ea to your computer and use it in GitHub Desktop.
Save maslade/6458190194faa80ee77d3833008506ea to your computer and use it in GitHub Desktop.
Examples for writing self-documenting code.
// Awful - hard to parse the grammar with your eyes, easier to mix up parentheses
navigator.geolocation.getCurrentPosition((loc) => this.located(loc.coords.latitude, loc.coords.longitude), () => this.located(lat, lng))
// Better - easy to parse out what is happening, but not the meaning... what are the arrow functions for?
navigator.geolocation.getCurrentPosition(
(loc) => this.located(loc.coords.latitude, loc.coords.longitude),
() => this.located(lat, lng)
)
// Good - I can tell exactly what's going on now.
navigator.geolocation.getCurrentPosition(
// success handler
(loc) => this.located(loc.coords.latitude, loc.coords.longitude),
// error handler
() => this.located(lat, lng)
)
// Best - the handlers will now show up as `onSuccess` or `onError` in stack traces. Looking at a
// call-stack 30 frames deep is **MUCH** more tenable when every frame has a meaningful name
// instead of "anonymous". It also makes the purpose of the callbacks clear without needing comments,
// which makes the code self-documenting (and in this case more concise).
onSuccess = (loc) => this.located(loc.coords.latitude, loc.coords.longitude)
onError = () => this.located(lat, lng)
navigator.geolocation.getCurrentPosition(onSuccess, onError)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment