Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many lines of code is too many for an asp.net mvc3 controller? [closed]

It depends.

a) Sure, but since the entire project gets turned into one .dll, does it really matter from a performance standpoint if you have 7 controllers with 300 lines of code each versus one controller with 2100 lines? (Obviously readability and tight coupling are problems if there is no separation of concerns)

b) As long as separation of concern is taken into consideration, is the number of lines of code in one controller not an issue?

c) How many lines of code in one controller can be a sign of needing to refactor? (500,1000,5000,10000)?

like image 956
Travis J Avatar asked Dec 21 '22 02:12

Travis J


1 Answers

Any fool can write code that a computer can understand. Good programmers write code that humans can understand. --Martin Fowler [ source]

I remember seeing an application in classic asp that was a single page. It rendered differently based on the parameters that came in. Theoretically, you could do the same thing with ASP.NET MVC, make a single controller with a ton of views (or worse a single view that changed based on input to the controller).

Granted, that super controller divides its work up into actions. But regardless, you're still working with something big.

The first SOLID Principle is Single Responsibility. Your module should have only one reason to change. A large controller tells me two things:

  1. It is involved with too much
  2. The actions have too much logic

Both of these are SRP violations because the Controller that does too much has more than one reason to change. The actions that do too much have to change when the logic changes or when the objects they interact with change.

To me a Controller Action should just call a function on a Service (interface, web service, whatever) and return the results of that call. Most of my controller actions are a whopping two lines of code. And most of my controllers are very focused in what they do.

As a rule of thumb, I get uncomfortable when I have to scroll more than two pages for a single class (about 200 lines depending on your font size and/or resolution). Even more important than actual length is how much responsibility my controller has. Minimize the responsibility and file size decreases automatically.

like image 149
Michael Brown Avatar answered Jan 01 '23 04:01

Michael Brown