I have been searching the web looking for a definition for declarative and imperative programming that would shed some light for me. However, the language used at some of the resources that I have found is daunting - for instance at Wikipedia. Does anyone have a real-world example that they could show me that might bring some perspective to this subject (perhaps in C#)?
Declarative programming is when you say what you want, and imperative language is when you say how to get what you want.
Imperative programming is a software development paradigm where functions are implicitly coded in every step required to solve a problem. In imperative programming, every operation is coded and the code itself specifies how the problem is to be solved, which means that pre-coded models are not called on.
Unlike the declarative approach, imperative programming emphasizes direct instruction on how the program executes functions. The code consists of a step-by-step sequence of command imperatives.
Functional is a particular kind of declarative. C, C++, Java, Javascript, BASIC, Python, Ruby, and most other programming languages are imperative. As a rule, if it has explicit loops (for, while, repeat) that change variables with explicit assignment operations at each loop, then it's imperative.
A great C# example of declarative vs. imperative programming is LINQ.
With imperative programming, you tell the compiler what you want to happen, step by step.
For example, let's start with this collection, and choose the odd numbers:
List<int> collection = new List<int> { 1, 2, 3, 4, 5 };
With imperative programming, we'd step through this, and decide what we want:
List<int> results = new List<int>(); foreach(var num in collection) { if (num % 2 != 0) results.Add(num); }
Here, we're saying:
With declarative programming, on the other hand, 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):
var results = collection.Where( num => num % 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."
In many cases, code will be a mixture of both designs, too, so it's not always black-and-white.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With