- Declarative Programming is a programming paradigm that focuses on what to execute, and defines program logic, but not detailed control flow
- Imperative Programming - is a programming paradigm that focuses on how to execute, and defines control flow as statements that change a program state
Declarative vs Imperative - Concrete Example
Click here to expand...
Problem
Given a list of numbers obtain all odd numbers
List<int> list = new List<int> { 1, 2, 3, 4, 5 };Solution
Declarative Solution
Imperative Solution
With declarative programming, you write code that describes what you want, but not necessarily how to get it (declare your desired results, but not the step-by-step):
List<int> results = list.filter(i -> i % 2 != 0);Here, we’re saying:
- give us everything where it’s odd
NOT “Step through the collection. Check this item, if it’s odd, add it to a result collection”
With imperative programming, we’d step through this, and decide what we want:
List<int> results = new List<int>(); foreach(var i in list) { if (i % 2 != 0) { results.add(i); } }Here, we’re saying:
- create a result collection
- step through each number in the collection
- check the number, if it’s odd, add it to the results
Declarative vs Imperative - Which is Better?
|
Parallel Computing |
|