Write Chatty Code

Nothing is more frustrating than when code is broken and the code isn’t helping you understand why its broken.

please fix. no logs tho.

Source: @arlieth

Odds are you don’t remember exactly how the code works so you need to read a lot of it just to figure out what’s wrong. While this is the norm in most cases, it diagnosing problems in code doesn’t have to be this painful.

One way to avoid getting caught in this situation is to write chatty code: code that regularly gives information about its internal operations in a human-readable format.

If you’re like me, your code has debug and log statements while you’re working on it; your code starts off chatty. For example, while working on a function, it might log multiple times in one call: beginning, after input validation and at the end.

function do_work( work ){
  console.log( 'received work' );

  // after validating input is valid work
  console.log( 'working on: #' + work.id, work );

  // DO WORK

  // after work is done
  console.log( 'completed work #' + work.id + ' in ' + duration + 'ms' ); 

This level of detail is probably too granular for production. A more acceptable granularity is a report on how the system performed over a given duration.

function do_work( work ){
  // after validating input is valid work
  // DO WORK

  // after work is done
  work.duration_ms = duration;
  completed_work.push( work ); 

setInterval( create_work_report, 1000 * 60 ); // every minute

function create_work_report(){
  // add total jobs to report
  // add slowest and fastest to report
  // add average work duration to report
  // add total failed to report
  console.log( 'worker-report: ', work_report );
  if( total_failed > 0 ) console.log( 'worker-report: failed: ', failed_work );

  completed_work = [];

This way, your code helps humans understand how it typically behaves and provides additional info when things don’t go as expected.

Make it easy to understand and fix your code. Make it chatty.

Get New Posts via Email

I don't always post, but when I do, you can get it sent directly to your inbox.

Join 16 other subscribers