Should we have one class for each responsibility in c++ ?

Hi ppl :),

My question is : Should we have one class for each responsibility in c++ ?

Consider an Eg. of Library Management System, we can have a design where in a student can search for a book based on it's title from the list of books using a function, something like below

[1]
1
2
3
4
std::vector<std::string> GetBookListBasedOnTitles(std::string title, std::vector<string> books) {
  // iterate through list of books and add a book to the result list if it's title is same as the title to be searched.
  // Return the result list.
}


or

[2]
shall we make an interface "Search" that will be implemented by "SearchByTitle" class and designate the responsibility of search functionality to that class.

[a] Are there any advantages [2] over [1], if yes, could you please give some scenarios explaining the same ?

[b] Shall we always make interfaces which can then be implemented by other classes to provide functionalities like Search, AddBook, AddMember etc. for the system? The negative which I see in this approach is there would be alot of interfaces for as for every small functionality, we have an interface.

[c] How to decide when to provide an interface for a functionality ?

Thanks alot for any inputs.
Last edited on
Should we have a class for every responsibility ?


The short answer is no.
Should we have one class for each responsibility in c++ ?
For the love of god and all that is good in the world, PLEASE NO!!

I've had to maintain (and in one case throw away and rewrite) code that was sort of like this. It meant hundreds of classes and hundreds of source files. When you look at each file, you don't see any of the context that it runs in, even if it only does one thing in one place in the code. The result was pure unintelligible spaghetti code.

As for the problem at hand, if you think you'll have to search by different criteria, you could pass a match function into a generic search function, but that pretty much requires you to use a linear search.

If you think about it, the issues of searching by arbitrary criteria is what databases are about. So if you need this, one could argue that you need a database.

shall we make an interface "Search" that will be implemented by "SearchByTitle" class and designate the responsibility of search functionality to that class.

In general, make the code as simple as possible while still providing the necessary and anticipated functionality.
dhayden wrote:
In general, make the code as simple as possible while still providing the necessary and anticipated functionality.
Very well phrased. +1
Last edited on
Thanks @dhayden and @Repeater for your inputs :)
Topic archived. No new replies allowed.