What is declarative code 2022.08.26

Some applications' code for saving and loading documents may consist of two separate functions kept in sync: one to translate the document into a stream of bytes and another for the inverse translation. Both mirror the document's format from different perspectives.

Suppose that you made a bug in one of these functions, or between other tasks you simply forgot to maintain it, such that the app's new feature may be saved but isn't loaded. We can hope that the QA team or the test suite would catch it.

This process is reminiscent to trying to ride two skateboards at the same time. Sometimes you would fall, go back to the skateboard left behind and try to do it again. Nailing it is an impressive feat! But when you are being chased by bugs and deadlines, wouldn't it have been easier if the boards were fused together?

Surfing on two surfboards

Tools like Protocol Buffers provide a saner solution. You'll only need to declare your data structure once, and it automatically implements both saving and loading. As a bonus, when using statically typed languages, it also creates the document's data types for you.

Command line arguments

(another example, skip to next session if you got the point)

Imagine getting an issue about a command line flag not working as described in the --help text, when you know that it's actually a deprecated option which was already removed! But apparently not from the help text..

This wouldn't happen when using libraries like argparse. When using it you provide a description of the command line arguments and get their parsing (with helpful error messages), and the help text both generated from it, always in sync!

Maintaining the help text separately is somewhat like hanging on to a unicycle when already sporting a jetpack. I think that we can leave the unicycle behind :)

Girl with a jetpack riding a unicycle

Declarative code

The use of Protocol Buffers or argparse as descrbied above is called Declarative Code. It means code which doesn't perform a computation of a single task (like saving a document), but rather describes an aspect's essence from which several different processes can be derived.

Here are a few additional examples:

Lens shedding light

The pros and cons of declarative code

What are the benefits and disadvantages of declarative code?



In addition to these, declarative code has an additional, perhaps more important advantage, at least for me: I just like it!

Riding a single skateboard is easier


The images for this post were all painted by the extremely talented DALL-E 2 per my requests. Here are some details on the process and links to their prompts:

I wish to thank OpenAI for creating this delightful artist!