Hacker News new | ask | show | jobs
by gerbilly 3857 days ago
OOP allows you to avoid code like this:

function makesound() { if( thing is a Cat ) return "meow"; else if (thing is a mouse) return "eep": else if (thing is a sheep) return "baa"; }

Code like this in an OOP language would be replaced by creating classes, such that the structure of the program implicitly executes the if else switch above, without you having to write it.

class Cat { makesound() { return "meow"; } }

class Mouse { makesound() { return :eep"; } } . . .

Then if all those classes inherit from a common animal ancestor, the calling code would simply say: animal.makesound()

This becomes very convenient when the program behaviour relies on a combination of two or more types.

In that case the if else example would have to contain nested and possibly repeated ifs (or calls to functions) to handle the logic for all the variations.

Note that inheritance in this example isn't to reuse code, just to establish the relationship between subtypes.

If you become tempted to use the type system as a clumsy code reuse mechanism, you will encounter alligators for sure.

Neither type of code is good or bad, just convenient for different purposes or not.

OOP is especially nice for writing simulations. See: https://en.wikipedia.org/wiki/Simula

1 comments

> Then if all those classes inherit from a common animal ancestor, the calling code would simply say: animal.makesound()

Which of course throws an exception in the case of Monk (inheriting from Animal -> Human), as it has taken a vow of silence.