Imperative vs Declarative Programming

This is a response to Tyler McGinnis’ article of the same name.

Like many before him, Mr. McGinnis tries to answer the question about imperative vs declarative with the old “what vs how” metaphor, but I think that misses the mark. It doesn’t tell us, for example if `a = b + c` is imperative or declarative, or what property would be necessary about the language in order for us to be able to make a determiniation.

So let’s take this simple code `a = b + c` as a basis and view the statement in a few different languages to get the idea:

When we write `a = b + c` in an imperative language, like C, we are assigning the current value of `b + c` to the variable `a` and nothing more. We aren’t making any fundamental statement about what `a` is. Rather, we are simply executing a step in a process.

When we write `a = b + c` in a declarative language, like Microsoft Excel, (yes, Excel is a programming language and probably the most declarative of them all,) we are asserting a relationship between `a`, `b` and `c` such that it is always the case that `a` is the sum of the other two. It’s not a step in a process, it’s an invariant, a guarantee, a declaration of truth.

Functional languages are declarative as well, but almost by accident. In Haskel for example `a = b + c` also asserts an invariant relationship, but only because b and c are immutable.

So yes, when objects are immutable and functions are side-effect free, code becomes declarative (even if it looks identical to imperative code,) but they aren’t the point. Nor is avoiding assignment. The point of declarative code is to make fundamental statements about relationships.

I started programming as a hobby in the late ’70s and professionally in the late ’90s. I am the director of development at Haneke Design.

I started programming as a hobby in the late ’70s and professionally in the late ’90s. I am the director of development at Haneke Design.