Tuesday, January 14, 2014

Difference between Procedural, Object-Based and Object-Oriented Approaches

Assume we need to develop a software that manages room temperatures by applying heat in to the rooms when necessary. The basic business is that each room has a desired temperature and current temperature. If the current temperature is lower than the desired temperature, then heat must be pumped into the room. But, if no one is there in the room, then temperature can be left to fall to 10 degrees below the desired temperature.

Procedural Approach:

We can write a HeatFlowRegulator program that gets the current & desired temperature for a given room number, and then a boolean to indicate whether anybody there in the room. The program then decides if heat should be applied in to the room or not.

Object-Based Approach:

We can write a HeatFlowRegulator program that gets a Room object and asks the object for its current & desired temperature and whether anybody there in the room or not. The program then decides if heat should be applied to the room or not.

Object-Oriented Approach:

We can write a HeatFlowRegulator program that gets a Room object and asks the Room object if it needs heat or not.

Hope the above example helps in showing the difference.

There is a principle called "Tell. Don't Ask" states that don't ask the object for its internal state and do take decisions based on that instead tell the object to do the things for you. In the above example the 2nd approach asks the object about its internal state and takes decision.

There is one more example I read somewhere sometime back on "Paper Boy". Paper Boy will always presents a Bill and requests the money to pay the paper bill rather than directly pulling your wallet and taking the bill amount needed.

It'll become very hard for object to change its internal representation if consumers tightly couple the code to its' internal state.

No comments:

Post a Comment