When would you deliberately write procedural style code instead of objects, and how do you show the difference between the two approaches?
You choose the procedural style when the code does one job, has one way of doing it, and nobody else is going to change it later.
public class Main {
public static void main(String[] args) {
double[] prices = { 100.0, 25.0, 12.5 };
System.out.println("procedural = " + totalWithTax(prices, 0.25));
System.out.println("objects = " + new OrderTotal().withTax(prices, 0.25));
}
static double totalWithTax(double[] prices, double rate) {
double sum = 0;
for (double price : prices) {
sum = sum + price;
}
return sum * (1 + rate);
}
}
So here are the signs that point to the procedural style.
the sign what it means
----------------------------------------- ------------------------------
the code runs once and is thrown away nobody will read it again
there is one behaviour and no reason a class would have one use
for a second one
the data is a plain list of numbers there is no state to protect
the whole thing fits on one screen splitting it up adds nothing
And the signs that point the other way.
the sign what it means
----------------------------------------- ------------------------------
the same calculation is needed in more the rules want to be shared
than one place
there is more than one way to do it the behaviour wants to vary
the data must stay consistent the class should check it
other people will change it it needs to be easy to extend
And there is one thing that is worth saying out loud. The two styles are not rivals and the choice is not about taste. It is about how much the code is going to change and who is going to change it. A code base with one author and one job is better in the procedural style, and a code base with many authors and many rules is better in the object style.
And there is a middle road that is worth knowing about, because it is what most real code looks like. You keep the plain functions for the calculations and you use objects for the things that hold state and have several behaviours. So the arithmetic in your service layer can be a static method and the order itself is an object, because an order has a state and it changes.
So the rule to remember is this. Write objects for the things that have state or more than one behaviour, and write plain functions for the rest.
The last question in this topic is about reusing code and changing behaviour.