Declarative vs. Imperative Programming Language
Declarative
- You use the code to describe what you want but not how to get it
- Real Life Example: I would like 5 red apples, please.
- Declarative Code Example: Select Top 5 * from FruitTable where Type=‘Apple’ and Colour=‘Red
Imperative
- You tell the compiler what you want and how you want to get it
- Real Life Example: I would like you to take all the fruit that you have and first get rid of all the fruit that is not apples, then with those apples I want you to look at each one and if it is red I want it, if not throw it away. Once I have 5 red apples you can stop sorting and then give me the fruit.
- Imperative Code Sample in C#:
List<Fruit> fruitList = GetFruit();
List<Fruit> apples = new List<Fruit>();
List<Fruit> redApples = new List<Fruit>();
int maxApples = 5;
int appleCount = 0;
foreach (Fruit theFruit in fruitList)
{
if (theFruit.Type == "Apple")
{
apples.Add(theFruit);
}
}
foreach (Fruit apple in apples)
{
if (appleCount < maxApples)
{
if (apple.Color == "Red")
{
redApples.Add(apple);
appleCount++;
}
}
else
{
break;
}
}
GiveFruit(redApples);
Obviously, there are better ways to perform a search for red apples, but this is just an example using the real-life steps.