2

I am a new user to programming and have started learning object oriented programming. It seems OOP is used to model real-life objects and interactions. My question is, should inanimate objects have behaviour?

For example should I have something like

class Room:
    clean()

or

class User:
    clean_room(Room)
oonoob
  • 23
  • 3

1 Answers1

1

Good question! You should have both.

The room can definitely have a clean() method, even if it's inanimate. In fact, this is practically necessary. If you pass a room to the User they will still have to call some public method in the Room class to perform the cleaning. clean() would be a suitable method for this. In fact, public methods exist so they can be used from the outside of the class, by some other class.

To be able to tell the User that he/she should clean the room, you also need a clean_room() method in the User class. This method will then call the clean() method on the Room object.

eli6
  • 964
  • 5
  • 15
  • Thank you, is this referred to as delegation when I am "forwarding" the clean_room call to room.clean? – oonoob Jun 19 '20 at 23:53
  • The simple "forwarding" to room.clean() is actually called just that: "Forwarding". Many people use the terms forwarding and delegation interchangeably. But delegation is strictly speaking a different concept where an object acts on behalf of another (knowing which object called the function). – eli6 Jun 21 '20 at 08:54
  • Here is a good explanation of the difference between forwarding and delegation: [Difference between forwarding and delegation](https://knowledge-capsule.site/en/difference-between-forwarding-and-delegation/). You can also check out this [discussion](https://stackoverflow.com/questions/7816011/in-oop-what-is-forwarding-and-how-is-it-different-from-delegation) – eli6 Jun 21 '20 at 08:54