Declarative programming vs Imperative programming

Are these examples, good examples to explain the difference between declarative programming and imperative programming

Yes, your streaming API example is somewhat declarative. But it might be too simple to understand the difference between declarative and imperative.

A good declarative example can be given using the kotlinx-html library.

Imperative example:

fun printPage(h1Text: String?, items: List<String>) {
    print("<html>")
    print("<head></head>")
    print("<body>")
    if (h1Text != null) {
        print("<h1>" + h1Text + "</h1>")
    }

    print("<ul>")
    for (item in items) {
        print("<li>" item  "</li>")
    }
    print("</ul>")
    print("</body>")
    print("</html>")
}

Same example, but declarative with kotlinx-html:

fun printPage(h1Text: String?, items: List<String>)  = System.out.appendHtml {
    html {
        head { }
        body {
            h1Text?.let {
                h1 { +it }
            }

            ul {
                items.forEach {
                    li { +it }
                }
            }
        }
    }
}

Both examples are kotlin code, and print the same html to the standard out. In the first example, it is very obvious how this is achieved. In the second example, the “how” is hidden away. It focuses on the “what”. The “how” vs “what” is often the differences between imperative and declarative programming.

if in the implementation [of the library] the logic is imperative style, even if I’m just using it, is my code still declarative?

It does not matter what paradigm was used to implement the kotlinx-html API (imperative, declarative, functional, oop, or a mix). The example code above is declarative in any case. In the end, every declarative framework is implemented on machine code, which is highly imperative mostly.

2 Likes