Thread: Why OOP?
View Single Post
Old Oct 13th, 2007, 8:42 PM   #44
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
I still can't quite see why you object so strongly to inheritance, as in many situations it provides a much cleaner solution than the procedural approach. For instance, take the following code:
python Syntax (Toggle Plain Text)
  1. class Player(object):
  2. def examine(self, name)
  3. item = self.find_item(name)
  4. item.on_examine(self)
  5.  
  6. def take(self, name):
  7. item = self.find_item(name)
  8. item.on_take(self)
  9.  
  10. def message(self, text):
  11. print text
  12.  
  13. def kill(self, killer):
  14. self.message("You were killed by a " + killer)
  15.  
  16. class Item:
  17. def __str__(self):
  18. return self.name
  19.  
  20. def on_examine(self, player):
  21. player.message(self.description)
  22.  
  23. def on_take(self, player):
  24. self.container.remove(self)
  25. player.inventory.append(self)
  26.  
  27. class LiveGrenade(Item):
  28. name = "live grenade"
  29. description = "Look out! It's a live grenade!"
  30.  
  31. def on_take(self, player):
  32. player.message("Kaboom! The grenade exploded when you picked it up!")
  33. player.kill(self)
The LiveGrenade class uses inheritance to override the on_take method. Indeed, the whole point of the OOP approach is that what a method actually does should be left up to the object. You're essentially just giving an object a message, and leaving the implementation up to it.

If I wanted to modify the above code to support multiple players, that wouldn't be too hard, either. I could have Player.message send the message to a TCP socket, rather than to STDOUT. I could even leave out the definition of the message method altogether, and have subclasses inheriting from it for single and multiplayer modes.

I'm curious as to how you'd write the above in a procedural style, and yet still retain the future flexibility that inheritance allows. For instance, let's say I wanted to have a squeaky toy:
python Syntax (Toggle Plain Text)
  1. class SqueakyToy(Item):
  2. def on_take(self, player):
  3. player.message("It squeaks as you pick it up")
  4. Item.on_take(self, player)
Or a gorgon head:
python Syntax (Toggle Plain Text)
  1. class GorgonHead(Item):
  2. def on_examine(self, player):
  3. player.message("As you look at it, you turn to stone")
  4. player.kill(self)
I don't see how this makes the code any less maintainable. It seems to do quite the opposite, in fact!
Arevos is offline   Reply With Quote