Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having a lot of methods in one controller VS having multiple controllers [closed]

Tags:

c#

asp.net-mvc

I'm developing an app and I am pondering over something. So I figured I would ask here for people with experience to tell me what they think about it.

So I have this controller (Store controller) which is huge and has a lots of methods, Get and Post actions, and so on in it. It works fine, but I'm still in development stage.

I am wondering what would be the best practice: to have this controller which holds so many methods and actions, or splitting the methods to many controllers? Is it ideal to have one controller deal with almost all of the methods, or many controllers?

And before you ask, yes, everything in my store controller is "store related". But in my store I have items, packages, and so on.

Edit

Thanks everyone! Following your advice, I have broken my huge Store controller into smaller controllers: one for the Items, one for the Packs, and so on. This indeed made the code more readable. Also, a lot of comments provided will put me on track for upgrade, so thanks a lot!

like image 324
hsim Avatar asked Jan 23 '14 14:01

hsim


1 Answers

It is definitely better to divide all your controller's actions into some logical packages - so to move them to separate controllers. Thanks to this it all becomes much more readable and intuitive for you also for other developers who will work on the project.

The question is: how to divide it?

There are in fact a few criterias that can influence such a decision for e.g.:

  • A controller should be connected with a certain set of logically connected pages. So for e.g. in case of an e-commerce platform you would probably have a CheckoutController, ProductController, UserAccountController etc.
  • You should also take into account which business concepts should be taken into account. In your case you have a concept Store, but as you are probably aware of this that it is a very broad concept in itself. So instead you should probably distinguish some more details in the business concepts.

A quite common approach is to divide controllers by CRUDs, although it is not always applicable. On the other hand your controllers should not be too granulated - so you should not exaggerate with it.

Please remember that ASP.NET MVC uses CoC (Convention over Configuration) approach which is also applicable to controllers and views naming conventions and the way they are grouped and placed in appropriate directories. When dividing your controller you should take this into account.

like image 102
Paweł Bejger Avatar answered Sep 30 '22 14:09

Paweł Bejger