Deciding whether to use parameters, conditional statements or subclasses
Archive - Originally posted on "The Horse's Mouth" - 2015-03-05 07:15:55 - Graham Ellis
"If you find yourself repeating a piece of code, there must be an easier way" But what if you have a number of similar but not identical items / things / objects?
If the things that change between each of your objects are just data values - for example the number and ages of childen - then you can handle the differences with parameters. If the things that change also require a logic change, you might use conditional statements such as if within your logic ... or if the changes are significant - a lot of them, and / or changing big blocks of code - you may choose to use a whole set of related object types.
Here's how it works:
• Code which is common to all your objects in a group goes into a base class
• Code which is type specific goes into a sub class which you declare to originate from (and thus inherit code from) the base class.
There's a practical example of that in use [here] from yesterday's Python course
- My base class is transport; it has two subclasses bus and train
- Common code (departure times, destination towns) are in the tranport base class
- Varying code (working out the capacity) is defined with different algorihms in bus and train subclasees
- Where there is a lot of common code within code in the subclass (but also variations), my subclass methods call another method that's shared in the base class.