Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a class too long? [closed]

Tags:

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.

like image 862
Dean J Avatar asked Feb 08 '10 15:02

Dean J


People also ask

How long should a class be C#?

In C#, my rule of thumb for classes is anything over 500 lines is getting too long.

How big should a class be OOP?

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.

How many methods can a class have?

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.


2 Answers

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]

like image 188
Steven Avatar answered Oct 25 '22 22:10

Steven


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!

like image 44
Sergey Teplyakov Avatar answered Oct 25 '22 21:10

Sergey Teplyakov