Imperative programming specifies how computation proceeds using statements that change the state of the program.
What we will be introduced in CS2030 is the concept of Imperative Programming. What we have learnt in CS1010J / CS1010S / CS1101S is the usage of Functional Programming, which is a form of Declarative Programming. Those who come from CS1010E, we have learnt basics of C programming language and procedural programming, which is a form of Imperative Programming.
Here some differences we can see in Imperative Programming Vs. Functional Programming.
Imperative | Functional |
---|---|
Performing tasks and Changing program state | Information and Transformations to be required |
Mainly manipulated using classes and structures | Mainly manipulated using functions and data |
Order of execution is important | Order of execution is not that important |
A key difference to note is that in imperative programs, Each assignment updates or changes the value of a variable,
allowing variable names to refer to different values at different points within the program itself.
Whereas in functional programs. Each function call should return a new value,
and that value can be used again as an argument for another function call. Mutation of variables usually does not exit here.1
This is an example of an imperative approach:
class FoodChecker {
int numOfExpiredFoods;
public FoodChecker(List foods) {
numOfExpiredFoods = 0;
for (food : foods) {
if (food.isExpired()) {
numOfExpiredFoods++;
}
}
}
public int getNumOfExpiredFoods() {
return this.numOfExpiredFoods;
}
}
This is an example of a functional approach:
class Main {
public static void main(String[] args) {
int numOfExpiredFoods = foods.stream().filter(food => food.isExpired()).count();
System.out.println(numOfExpiredFoods);
}
}