Today I had a discussion about coding guidelines and in particular about the size of a class, the number of methods in a class and the number of lines of code per class. What is right?
Ofcourse a little search on Google revealed millions of hits. Some of the more useful ones were:
Most standards don't say much about the size of a class, the number of methods in a class and the number of lines of code per class. The few that do say something come fairly close.
Here's the sum of guidelines that I think I'll stick by:
- A source file should only contain one class
- A method should be no more than 30 lines of code, excluding blank lines and comments
- A source file should contain no more than 1000 lines, including blanks and comments
- An interface should have no more than 10 methods, excluding overloads, ie. the combination of overloads counts as one methods
- C# 2.0 allows partial classes:
- a source file should only contain one partial class
- don't split the implementation of an interface across multiple files
- for large classes split the implementation of interfaces and implement one interface per file
- Filename: <classname>.<interfacename>.cs
- if you have a class which implements one interace, but has a lot of private methods, then create a partial class with just the private methods:
- Filename: <classname>.private.cs
Ad 2.
This is the average I found and seems to make sense, since this means that with one look at the screen your brain can absorb the whole method.
Ad 3.
I'm not convinced this is a very important rule. Having 2000 lines of code in one file or spread across two classes in two files doesn't really make that big a difference to me. See also ad 5.
Ad 4.
This is mainly because of Intellisense. Ten methods will provide optimum use of Intellisense.
Ad 5.
Partial classes are great!