Object-Oriented Design – Determining Which Object Should Have the Method

methodsobject-orientedobject-oriented-designrefactoringsolid

I am trying to create an object model for a user and a chatroom. I'm stuck on where to place certain functionality when the objects collaborate.

At the moment all the functionality for the User is inside the User class, a snippet of its methods are:

  • User.JoinChatRoom()
  • User.WriteChatRoomMessage()
  • User.Authenticate()
  • User.JoinGroup()

I recognize that is this is a "God Object"/"Blob"" and instead we could model this as seperate objects ChatRoom, User and Group with the methods:

  • User.Authenticate()
  • ChatRoom.AddPlayer(User u)
  • ChatRoom.WriteMessage(String msg)
  • Group.AddPlayer(User u)

But I am confused about this refactor since, the way I understand object methods is that they perform an operation on the object. Therefore you can command the user to write to a chatroom, command the user to join a group, etc.

But with the "cleaner" second model this doesn't seem to fit, there is no explicit JoinChatRoom() method.

How do I design and think about what methods should be attached to an object?

Best Answer

In your case, you have users vs. Chatrooms. If you have methods that concern both, you could put them into either class, not much difference.

However: You will have not only users vs. Chatrooms, you will have Users vs. bills, users vs. Support requests, users vs. 100 other things. If you do things consistently by putting methods into the user class, it will explode in size.

The other problem is that whoever maintains the chatroom code probably knows better how to add a user to a chatroom than the person maintaining the user code. Adding a user is probably not trivial and will require calls to various chatroom methods that you’d prefer to be private. So you will get simpler code written by the person who knows about chatrooms if you add the method to the chatroom class.

Related Topic