C++ Design – How to Split Up Large Interfaces

cdesigninterfaces

I'm using a large interface with about 50 methods to access a database. The interface has been written by a colleague of mine. We discussed this:

Me: 50 methods is too much. It's a code smell.
Colleague: What shall I do about it? You want the DB access – you have it.
Me: Yeah, but it's unclear and hardly maintainable in the future.
Colleague: OK, you are right, it's not nice. How should the interface look like then?
Me: How about 5 methods that return objects that have, like, 10 methods each?

Mmmh, but wouldn't this be the same? Does this really lead to more clarity? Is it worth the effort?

Every now and then I'm in a situation where I want an interface and the first thing that comes to mind is one, big interface. Is there a general design pattern for this?


Update (responding to SJuan's comment):

The "kind of methods": It's an interface for fetching data from a database. All methods have the form (pseudocode)

List<Typename> createTablenameList()

Methods and tables are not exactly in a 1-1-relation, the emphasis is more on the fact that you always get some kind of list that comes from a database.

Best Answer

Yes, 50 methods is a code smell, but a code smell means to take a second look at it, not that it's automatically wrong. If every client using that class potentially needs all 50 methods, there may not be a case to split it. However, this is unlikely. My point is, splitting an interface arbitrarily can be worse than not splitting it at all.

There isn't a single pattern to fix it, but the principle that describes the desired state is the Interface Segregation Principle (the 'I' in SOLID), which states that no client should be forced to depend on methods it doesn't use.

The ISP description does give you a hint on how to fix it: look at the client. Often, just by looking at a class it seems like everything belongs together, but clear divisions emerge when you look at the clients using that class. Always consider the clients first when designing an interface.

The other way to determine if and where an interface should be split is by making a second implementation. What often ends up happening is your second implementation doesn't need a lot of the methods, so those clearly should be split off into their own interface.

Related Topic