When is a function too long? is a subset of this question, I think.
What are a few good metrics for determining that a class is too long?
I'm rerevising a set of code acceptance guidelines for a project with external contractors, and realized I haven't covered this in the past, but should cover this in the future.
In C#, my rule of thumb for classes is anything over 500 lines is getting too long.
Like functions, according to Clean Code, classes should also be “smaller than small”. Some people recommend that 200 lines is a good limit for a class – not a method, or as few as 50-60 lines (in Ben Nadel's Object Calisthenics exercise)and that a class should consist of “less than 10” or “not more than 20” methods.
The number of methods that may be declared by a class or interface is limited to 65535 by the size of the methods_count item of the ClassFile structure (§4.1). Note that the value of the methods_count item of the ClassFile structure does not include methods that are inherited from superclasses or superinterfaces.
When it has more than one responsibility.
Let me quote Robert C. Martin's Clean Code here:
The first rule of classes is that they should be small. The second rule of classes is that they should be smaller than that. ... With functions we measured size by counting physical lines. With classes we use a different measure. We count responsibilities. [Chapter 10, page 136]
Class fan-out complexity: The number of other classes a given class relies on. Also the square of this has been shown to indicate the amount of maintenence required in functional programs (on a file basis) at least.
Cyclomatic complexity: Checks cyclomatic complexity against a specified limit. The complexity is measured by the number of if, while, do, for, ?:, catch, switch, case statements, and operators && and || (plus one) in the body of a constructor, method, static initializer, or instance initializer. It is a measure of the minimum number of possible paths through the source and therefore the number of required tests. Generally 1-4 is considered good, 5-7 ok, 8-10 consider re-factoring, and 11+ re-factor now!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With