Declarative Statement

A declarative statement has no timing of execution.

The statement list.push('item') executes at a specific point in time. When it executes, it adds an item to the end of our list. If the list is then sorted that item would likely change places in the list. If, however, the list had already been sorted the sort operation would have to affect on the outcome of our push. The push operation can execute multiple times, and each time in will add another item to the list. It could also never execute, having no affect. list.push is an imperative operation—an operation which executes at distinct points in time—and it is can lead to complexities.

Consider a hypothetical system which allows us to define a reactive list. This list would be defined with some conditions, and will be kept up to date by some magic system so that it always satisfies those conditions.

var oddBalls = from ball in balls
			   where ball.number % 2 == 1
			   select ball;

In fact, this system does exist. This is an example of using LINQ in C# with Reactive Extensions. LINQ is the language extension which allows us to type these semantics, (from, where, and ball) but Reactive Extensions is the system which keeps list up-to-date. RX, as it's called, will observe balls for changes, and will insert or remove items from oddBalls as necessary so that it is always a filtered variant of the current balls.

Reactive Extensions, unfortunately, is not actually fully declarative. Luckily, there is another, more common example of declarative code—one which is so simple it is often not considered to be code at all.

CSS is a purely declarative language.

.balls:nth-child(odd) {
	background: red;

This statement is similar to the RX statement, but it satisfies all requirements to be considered declarative.

As I've said, CSS's declarative nature makes its execution so simple that it's often not considered to even be a programming language. Imagine, however, that CSS was imperative. This rule would need to observe all changes to the document structure—adding and removing elements, changing order, updating classes. The code would then need to update any newly found odd-numbered children of a .balls element with a red background. Much harder than all of that, our imperative code would need to reverse the effect on any balls which stopped being odd. This operation could not simply set the background of the element to the default, but would need to scour the existing HTML elements and CSS rules for whichever rule might now need to be applied. These operations would be incredibly expensive, and very difficult to optimize.

Fortunately, CSS is declarative, and as such we can write our simple little statement, and get on with our simple little lives.

#complexity #software