Sign up ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

In your experience, what is a useful rule of thumb for how many lines of code are too many for one class in Java?

To be clear, I know that number of lines is not even close to the real standard to use for what should be in a particular class and what shouldn't. Classes should be designed according to proper OOP philosophies (encapsulation, etc.) in mind. That said, a rule of thumb could provide a useful starting point for refactoring considerations (i.e. "Hmmm, this class has >n lines of code; it's probably unreadable and doing a lousy job of encapsulation, so I might want to see if it should be refactored at some point").

On the flip side, perhaps have you encountered examples of very large classes that still obeyed OOP design well and were readable and maintainable despite their length?

Here's a related, non-duplicate question about lines per function.

share|improve this question

closed as primarily opinion-based by Robert Harvey, MichaelT, Dan Pichelman, Dynamic, gnat Jul 14 '13 at 23:11

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise.If this question can be reworded to fit the rules in the help center, please edit the question.

I've seen classes with more than a thousand lines, I don't think there's such thing as "too many". – Mahmoud Hossam Apr 8 '11 at 17:24
It's too many when it won't compile any more. Seriously, it's only too many when the class is doing too many different things. – Berin Loritsch Apr 8 '11 at 17:35
A rule of thumb turns into a maximum which turns into a policy which turns into a disagreement. Avoid numerosity. Counting and measuring aren't the ideal way to establish if responsibilities were allocated properly. – S.Lott Apr 8 '11 at 17:46
About the same as the correct number of inches for a piece of string. – Matt Apr 8 '11 at 17:53
@Mahmoud: too many is relative, but it's real. Whether you think 1000 isn't too many or 100 is too many, 10.000 would be excessive I think to any professional :) I'm currently maintaining a 5000+ line monstrosity, and doing what I can to cut it down to size just to make it maintainable (currently, my IDE needs several minutes to parse the thing for syntax checking, it's that bad). – jwenting Apr 8 '11 at 20:08

10 Answers 10

Clean Code:

Classes Should Be Small!

The first rule of classes is that they should be small. The second rule of classes is that they should be smaller than that. No, we’re not going to repeat the exact same text from the Functions chapter. But as with functions, smaller is the primary rule when it comes to designing classes. As with functions, our immediate question is always “How small?”

** With functions we measured size by counting physical lines. With classes we use a different measure. We count responsibilities.**

The name of a class should describe what responsibilities it fulfills. In fact, naming is probably the first way of helping determine class size. If we cannot derive a concise name for a class, then it’s likely too large. The more ambiguous the class name, the more likely it has too many responsibilities. For example, class names including weasel words like Processor or Manager or Super often hint at unfortunate aggregation of responsibilities.


  • Just make sure your methods do only one thing.
  • Then make sure the class doesn't have too many responsabilities.

You will end up with a class of a manageable size.

share|improve this answer
if Clean Code on top of your answer refers to the book by Robert C. Martin (which it does!), then I have to say you and I have it in common; that book is what led me to this question. I think this answer says it all – Suhail Jul 31 at 9:49

Any line that falls within your class's problem domain written outside of the class is one line too few and one too many in the class where it lives. Think of a class as a topic. You have to cover it. As concisely as possible is ideal but if it takes 500 lines, it takes 500 lines. If 100 of those lines cover another topic, they belong somewhere else. Breaking into smaller subdomains within the class as interior classes makes sense but I would only define those outside of the class if they had use elsewhere.

share|improve this answer

The correct answer is 42. Just kidding.
Actually, the maximum recommended lines per class is 2000 lines.

"Java Code Conventions" since 1999 have stated it this way:
Files longer than 2000 lines are cumbersome and should be avoided.

Having followed Sun/Oracle Coding conventions since Java was invented, I've found this rule of thumb on lines per class to be reasonable. 99% of your Java Code should conform... And if it goes over 2000, just put a TODO at the top saying the class needs work.

The worst thing is the opposite case when programmers create too many tiny little classes with almost no real functionality in each class. Ignoring the advice to "Favor Composition", programmers create hundreds of inheriting classes which create complicated object models that are far worse than the large class problem (which at least usually keep functionality with a relevant class name).

share|improve this answer

I'm sorry but I'm very surprised that many answers state that it "doesn't really matter". It very MUCH matters how many lines are in a class. Why? Consider these principles in writing good Java code...

  • Testability
  • Cohesion
  • Coupling
  • Understandability

Classes with lots of lines in them will most likely violate all of those principles.

For those who have stated it "doesn't really matter" much fun has it been for you to try and understand a class that has 5000+ lines in it? Or, to modify it? If you say that's fun, you've got a strange affinity towards pain...

I would say any class that has greater than 1000 lines in it should at least be questioned in how they may be violating the principles above and possibly parsed out into several "off-shoot" classes.

My comments are based off of reading and studying such authors as Martin Fowler, Joshua Bloch and Misko Hevery. They are excellent resources to consult for writing good Java code.

Do the next guy (which could be you in a couple of years) a favor and strive to write classes that have fewer rather than more lines in them.

share|improve this answer
I think everybody agrees that 5000+ is not generally a good sign (not counting nested classes), but they feel like it's more of a side effect or something than the actual problem. Of course, some people are overly verbose and use an excessive number of lines just to declare and initialize variables and such - and they need to stop that. That does make it less readable. But if it relates to class structure, the problem isn't the LOC itself; it's the fact that somebody just isn't breaking things up very well to begin with, and the LOC is a side effect of that. – Panzercrisis Jul 31 at 13:36

Try using a better metric.

One example is the ABC Metric. It is more a measure of how much work is being done by the code than how much code there is.

share|improve this answer

Some interesting metrics:

            junit  fitnesse testNG    tam     jdepend    ant     tomcat
            -----  -------- ------    ---     -------    ---     ------
max           500       498   1450    355         668   2168       5457
mean         64.0      77.6   62.7   95.3       128.8  215.9      261.6
min             4         6      4     10          20      3         12
sigma          75        76     110    78         129    261        369
files          90       632   1152     69          55    954       1468
total lines  5756     49063   72273  6575        7085 206001     384026

I use FitNesse as a benchmark because I had a lot to do with writing it. In FitNesse the average class is 77 lines long. None are longer than 498 lines. And the standard deviation is 76 lines. That means that the vast majority of classes are less than 150 lines. Even Tomcat, that has one class in excess of 5000 lines, has most classes less than 500 lines.

Given this we can probably use 200 lines as a good guideline to stay below.

share|improve this answer
If the class has only one responsibility, chances of it going above 200-500 lines are pretty slim. The ones that do typically have "inner classes" to handle other related responsibilities. For example, the Tomcat 5000+ line class might really be 1 main class with a dozen inner classes. That's not unusual in Java where you have request handlers and such. – Berin Loritsch Apr 11 '11 at 12:43
how are these metrics obtained, really? just want to know – Suhail Jul 31 at 9:41
I'd usually lean more towards this answer on the linked question relating to functions: LOC is kind of irrelevant, except as maybe an extremely general rule of thumb to simply start wondering if you might be able to break things down further. And I agree about the nested classes thing. Nonetheless, 500 is probably closer to a general warning sign. – Panzercrisis Jul 31 at 13:17

Number of lines is a pretty poor metric for class quality. For me, I like to look (as others have mentioned) at public methods, as well as any publicly exposed properties (I guess public getters/setters in Java). If I had to pull a number out of the air for when it might catch my attention, I would say when there are more than 10 of each. Really, if its more than about 5 of either properties or methods, I will take a look and often find ways to refactor, but anything over 10 is usually a warning sign that something is fairly likely to be poorly exposed.

Its another conversation entirely, but private methods and fields are less of a smell for me, so if they are contributing a lot to the number of lines, then I might not be as worried. At the very least, it shows that there probably is not some God controller maniplating the object from afar, which is a pretty problem design problem.

share|improve this answer

There are too many lines of code if the class is doing too many different things. Essentially, if you follow the principle of Single Responsibility for classes, there is a limit to how large the class will grow.

As to physical limitations you can have (source: Class file format Java5):

  • 65,536 constants, interfaces applied, fields, methods, and attributes--each. NOTE: you will run out of constant space before you run out of any of the other items. NOTE 2: attributes are class file constructs--not to be confused with '@Attribute' markers (i.e. debug info and byte code are stored as separate attributes for a method).
  • Each method can be 4GB (32 bits) of generated byte code. NOTE: Java versions prior to 1.5 could only have 64KB (16 bits) of generated byte code for each method.

In short, the class file can be much larger than anyone would consider useful. If you stick to the single responsibility principle, your class files will be the right size.

share|improve this answer
+1 for single responsibility :) @Berin do you implement this strictly in your software? – Aditya P Apr 8 '11 at 18:03
Yes. The trick is to divide the responsibilities in a way that makes sense. – Berin Loritsch Apr 8 '11 at 18:17
ah, the good old 64KB boundary. Nice lithmus test to see whether your JSPs are too complex, as they get translated into a single method with lots of println statements for all your static html :) – jwenting Apr 8 '11 at 20:43
As of Java 5, they've increased it to 4GB. No worries there now. – Berin Loritsch Apr 8 '11 at 21:42

It depends on the complexity, not the number of lines. I've written big dumb routines that were easy to understand and which did precisely one thing and did it well, but went on for hundreds of lines. I've written fairly short functions that were hard to understand (and debug).

Another thing you could look at is the number of public functions in a class. That can also be a warning sign.

I don't have good counts available, but I'd suggest looking at some decent code that does useful things at your shop, and basing it off that. Certainly you should look at the longest classes and the biggest APIs.

share|improve this answer
+1: Don't measure dumb things like lines. Cyclomatic Complexity and Feature Counts (number of methods) make more sense the lines. – S.Lott Apr 8 '11 at 17:47
yes and no. An excessive number of lines is often a symptom of bad design, and thus a red flag that the class likely needs refactoring. – jwenting Apr 8 '11 at 20:10
@jwenting Yes, that's what I was getting at. I know lots of lines != needs to be refactored, but almost all of the classes I'm working with that really need to be refactored due to poor design have lots of lines. – Michael McGowan Apr 8 '11 at 20:29

For me, lines of code is irrelevant in this context. It's all about the number of different reasons I would come to this class to change it.

If I would come to this class when I want to change the rules for validating a Person, I don't want to come to the same class to change the rules for validating an Order, nor do I want to come here to change where I persist a Person.

That said, if you aim for that then you will rarely find classes more than 200 lines. They will happen, for valid reasons, but they'll be rare. So if you're looking for a red-flag metric then that's not a bad place to start; but make it a guideline, not a rule.

share|improve this answer
200 feels about right as a very rough guess. Like you say, not the thing you worry about first though. – Steve Haigh Apr 8 '11 at 17:37
The othing thing about Java is, when counting LOCs I would ignore the getters/setters. – MrFox Feb 7 '13 at 16:12
@MrFox: I disagree. If your class has enough getters and setters to skew LOC data, that counts against it in the "is this class doing too much?" question. However, as a compromise I'd be willing NetBean getter/setters at less than 1 line/line out of respect for the excessive boiler-plate such methods have. – Brian Jul 12 '13 at 19:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.