Object-oriented – How to decide to which class a method should belong

designobject-orientedobject-oriented-design

I have TopicBusiness.class and PostBusiness.class. I have no problem with deciding into which class methods such as addPostToDatabase() or getAllPostsFromDatabase() should go. But what about getAllPostsFromTopic(TopicEntity topic) or getNumberOfPostsInTopic(TopicEntity topic)?

Should the parameter be the deciding factor? So when the method takes TopicEntity as parameter it should belong to TopicBusiness.class? I am quite puzzled by this.

EDIT:

Some more info as requested. TopicBusiness.class and PostBusiness.class are classes holding all the business logic of the application concerning topics and posts respectively – that is fetching the data from database and/or performing some operations on them.

TopicEntity is data (in this case representing single topic) fetched from database. getAllPostFromTopic(TopicEntity topic) gets all posts from database that belong to particular topic, while getNumberOfPostsInTopic(TopicEntity topic) performs database query and returns the number of posts that topic passed as parameter consists of.

Best Answer

As a Topic can have multiple Posts, the TopicEntity.class should know what and how many PostEntitys it has, so Topics could have a getPosts() method instead of using another method which uses TopicEntity as parameter.

However if you need such a method for special purposes I'd say:

The method belongs to that business class which the result is belonging to.

On the concrete example this means:

getAllPostsFromTopic(TopicEntity topic) gets PostEntities, and getNumberOfPostsInTopic(TopicEntity topic) gets information about a subset of Posts, so both clearly belong to PostBusiness.class.

This is also intended by the choise of the methods names:

getAllPostsWhichAreOf(predicate)

getNumberOfPostsWhichAreOf(predicate)