What is polymorphism?
Explanation by Analogy
The President of the United States employs polymorphism. How? Well, he has many advisers:
- Military Advisers
- Legal Advisers
- Nuclear physicists (as advisers)
- Medical advisers
- etc etc.
Everyone Should only be responsible for one thing:
I promise you that the president knows absolutely nothing about Geophysics, or stem cells etc - nor should he know. That’s not his job or responsibility. Those tasks should be left to experts who spcecialise in those fields.
Example:
Would it make any sense for the president to say to congress: “We need to make a law requiring 0.2mm coating on all on iron and steel products within 250m of saltwater to prevent corrosion”? Obviously not. It’s the same with code: those concerns should be separated to the relevant classes/people. Otherwise you’d have the president knowing literally everything in the world - the entire Wikipedia, in the President class. it would be a nightmare to maintain.
Why is that a bad idea for a president to know all these specific things?
If the president were to specifically tell people what to do, that would mean that the president needs to know exactly what to do.
There is a better approach: the president does not need to know anything - he can demand the best advice, from people specifically tasked with doing those things. He can use a polymorphic approach to running the country.
Example - What you should do in your code
All the president does is ask people to advise him - and that’s what he actually does in real life - and that’s what a good president should do. his advisors all respond differently, but they all know what the president means by: Advise(). For example:
public void RunTheCountry() - see below:
- Petraeus.Advise() // # send 100,000 troops to Fallujah
- Condolezza.Advise() // # negotiate trade deal with Iran
- HealthOfficials.Advise() // # We need to spend $50 billion on ObamaCare
This approach allows the president to run the country literally without knowing anything about military stuff, or health care or international diplomacy: the details are left to the experts.
What you DON”T want:
public void RunTheCountry()
// Fallujah Advice - Mr Prez tells his military exactly what to do.
- Petraeus.IncreaseTroopNumbers()
- Petraeus.ImproveSecurity()
- Petraeus.PayContractors()
// Condi diplomacy advice - Prez tells Condi how to negotiate
- Condi.StallNegotiations()
- Condi.LowBallFigure()
// Health care
- HealthOfficials.IncreasePremiums()
- HealthOfficials.AddPreexistingConditions()
NO! NO! NO! In the above scenario, the president is doing all the work: he knows about increasing troop numbers and pre-existing conditions. All of that should be left to the experts.
This allows the president to do what he does best: set general policy, look good and play golf :P
That in effect is polymorphism.
I really hope it helps you. If you don’t understand anything post a comment and i’ll change the answer.