Procedural programming follows top down approach. Control flows from the top to
the bottom.
Let's assume that we are building a ticketing system for a park. Right now there
is only one rule. The adults will pay the full price and the young people, who
are of age less than 18, will get a 20% discount on the price.
Let's see how we can implement this solution using procedural style of
programming.
In the above case we have a method called is_young
. It's a bit of
simplification but in the older programming languages it is also called
subroutines or procedures. This is why this style of programming is called
"procedural style" because this style makes use of procedures.
In the Object Oriented World we would solve the same problem using classes.
Let's now solve the same problem using Object Oriented style.
Both the style of programming gets the work done. However the procedural style
takes only 11 lines of code while the object oriented style takes a whopping 30
lines of code.
At this time it might seem that procedural style of programming is better. It's
shorter and it's easier to follow.
Summer break and more discounts
Our park is doing well and after a few months of the opening of the park we got
the following requirements.
- All folks above the age of 60 should have 10% discount.
- All Adults will get 5% discount but only on Tuesdays.
- During summer break (month of June) people below the age of 18 will get an
additional 10% discount.
Let's incorporate the above requirements in the procedural style first.
Here is the Object Oriented version.
Notice that in the Procedural style we keep adding methods as we need them
because of its top down approach.
In the Object Oriented style we have a place for everything. Anything that has
to do with the attributes of a person will go to the Person
class and anything
that has to do with ticket and pricing will go to the Ticket
class.
In the Object Oriented style if the complexity in the Ticket
class grows too
much the we can create a new classes to take some load off of the Ticket
class.
Group buying and reservations
A few months later we got some new requirements.
- People should be able buy tickets online for future date. It means now we need
to deal with reservation. People should be able to cancel the reservations.
- Park has limited parking facility and now folks can also reserve parking spot.
- Park has started offering group purchase. If a group of 10 people buy the
tickets together then there is 20% discount. If the group consists of 20
people or more than there is 25% discount.
As we can see the complexity in the logic keeps increasing.
In a procedural style because of its top down approach we will have many methods
all one after another and soon things will be less manageable.
In the Object Oriented style we can create new classes like Reservation
,
GroupPurchase
, Parking
to manage such complexities.