OdeToCode IC Logo

Declarative Versus Imperative Coding

Monday, February 13, 2006

andyclap commented on my recent “Life With XAML” article:

“Did the brave OO language research guys give (the better part of) their lives in vain; their graves to be desecrated by the vile 1970s SGML nincompoops?

From this sample, the only function of XAML seems to be to put the foul-tasting XML syntactic sugar around a very ordinary presentation paradigm.”

Colorful language, andyclap, I enjoyed reading the entire comment. I wish my article had gotten across the point that object orientation isn’t dead with declarative markup. Many of the articles I’ve read about WPF (a.k.a. Avalon) overstress the loving embrace of angled brackets, and I tried to put in a slightly different spin. Non-trivial WPF applications still need both declarative XAML and imperative code.

In many scenarios it’s easier to describe what the goal is that you want to achieve, instead of descrtibing how to get to the goal.

I’ll turn again to an ASP.NET example. Here is some code imperatively building part of a webform.

Label label = new Label();
label.ID =

Panel panel = new Panel();
panel.ID =


We must specify the commands to reach the goal: we want the form to contain a Panel object, and the Panel object to contain a Label object. Unfortunately, all the commands obscure the goal, particularly as we add more controls and a deeper hierarchy. It’s not surprising that ASP.NET lets us use a declarative style, as HTML is a declarative language and the two need to intermingle. The declarative form would look like the following:

<form id="form1" runat="server">
    <asp:Panel runat="server" ID="Panel1">
        <asp:Label runat="server" ID="Label1" />

In the declarative form, the goal is easier to see, and consequently easier to understand, maintain, and modify. Declarative programming is also easier for tools to understand, which leads to more designers to visualize declarative programming compared to imperative programming.

Still, everything we do in software requires a tradeoff, and declarative programming isn’t well suited for every task. In my article I decided it was easier to use imperative code and a loop to define a grid instead of using XAML. On the other hand, workflows come to mind as a tasks that are easier to specify declaratively. Since the runtime and our hardware are all imperative, imperative programming will still be around for a long time.