Should a like method go on User or Post?

November 12, 2026 4 answers
Asked by inbox detective

I'm learning object-oriented programming and trying to figure out where an action belongs. A user likes a post, but the like also changes data associated with the post.

Would you put the method on User because it performs the action, or on Post because it owns the like count? What should guide that choice?

Answers

-sideways ketchup

Start with the object that owns the state and the rules for changing it. If Post owns the like count, give it a method such as post.add_like(user) rather than letting User directly change the count.

That keeps the update behind Post's API. If you later change how likes are stored or counted, callers don't necessarily need to know. Passing the user also gives Post enough information to apply rules such as preventing duplicate likes, if that's a requirement.

not-yet-folded:

A bare count may be enough for a simple example, but it can't by itself tell you whether a particular user has already liked the post.

Reply to this answer
v7-Daxlow

Both methods can make sense because they can have different jobs. user.like(post) might express the action at the call site, while it delegates the actual update to post.add_like(user). User doesn't need to reach into Post's fields.

That extra method is only useful if it makes the surrounding code clearer or User has its own rules to enforce. If it's just a one-line wrapper nobody needs, calling the Post method directly is simpler.

Reply to this answer
PLEASE STAND BY-ish

There's another way to model this: a like is a relationship between a user and a post, not necessarily a field owned by either one. If you need to record who liked what, a separate Like object or relationship store may fit better. The post's count can then be derived from those records rather than treated as the whole story.

In that design, a function or service that receives both the user and the post can coordinate the operation. It doesn't have to be a method on either class just because the action involves both of them.

speling_bee_dropout:

That does add another piece to the design, though. For a toy example where only the total matters, a count on Post might be plenty.

Reply to this answer
after_the_bell

Watch out for turning User into the place for every action a user can perform. Likes, comments, posts, and whatever comes next can make that class depend on a lot of unrelated parts of the system. Putting behavior near the relevant domain object can keep those dependencies smaller.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions