When to Have More Than One Controller Class in Java MVC

controllerjavamvc

Would it be correct to assume that in general, I would need as many controller classes as classes that can be accessed/modified by a user?

For example, If a logged-in user can add/modify to a class clients, addresses and stores, I would need a controller for each class?

thanks

Best Answer

Things may seem to play out that way in some projects, but I wouldn't give any specific consideration to it.

A controller is basically a collection unit of semantically related methods (at least that's how I've always thought of them). That's probably not true all the time, but enough for government work, as the saying goes.

Many times, that tends to map somewhat closely to your "main business logic" classes, in that you tend to wind up with a controller for Clients, another for Staff, etc.

More often though controllers may tend to follow a context of what page(s) are being used. Working with a Clients page in the UI, for example, might also have relevant addresses to manage, in which case it can make sense to include an Address post method in your Clients controller.

But on the other hand, if you're using an API that's intended to be shared by multiple systems, such contexts aren't quite as applicable. In either case though, I don't think too many people would insist on having an Addresses controller to handle basic addressing needs of a Client. Make use of semantics and pragmatic grouping/contexts, and the two will go together (in fact, I might say that an Address for a Client might be submitted as part of a Client's POST/PUT operation, so maybe no need for a method to handle addresses, let alone its own controller)

Related Topic