Imperative vs Declarative Programming
A case study using Kubernetes to help you understand them from confusion to clarity.
I recently need to work with a partner team who decides to use declarative code rather than configuration for user to author APIs. After reviewing the design doc, I was wondering what exactly is declarative code, how does it apply to this use case and what are the common scenarios where it is preferred, so I took some time to research on it.
I’m not the only one have this question, if you search “What is the difference between imperative and declarative programming”, Google will yield a lot results.
According to Wikipedia, “In computer science, declarative programming is a programming paradigm—a style of building the structure and elements of computer programs—that expresses the logic of a computation without describing its control flow.” In addition, “Declarative programming is a non-imperative style of programming in which programs describe their desired results without explicitly listing commands or steps that must be performed.” And here is a comparison:
Imperative programming – focuses on how to execute, defines control flow as statements that change a program state.
Declarative programming – focuses on what to execute, defines program logic, but not detailed control flow.
This is still not crystal clear to many. The example code and tool used in wiki are written in programming languages that people rarely use in daily life, so I decided to write a more relevant example using Kubernetes.
Why do I choose Kubernetes as example? Because (1) Kubernetes is widely used nowadays with Cloud and containerization fairly common today. Even if you have never used, you probably want to learn it. (2) Kubernetes use both imperative and declarative programming extensively hence it’s good for illustration the differences and usage of both.
Keep reading with a 7-day free trial
Subscribe to CodeInBusiness to keep reading this post and get 7 days of free access to the full post archives.