old mainframe

Create Small Classes

It’s a good idea to write small classes. Classes are about cohesion, i.e. putting things together that belong together. There should be relatively little code that naturally associates. On the other hand, when we have large classes with many methods, it’s a sign of trouble.

What do I mean by large classes with many methods?

I have found around 500 lines of code to be a maximum for a class—most of my classes have fewer than 200 lines of code.

Similarly, when the number of methods exceeds about a dozen (12), the class is likely doing too much.

These are not hard and fast rules. On occasion, I end up with more methods or lines. However, as a class approaches these limits, I ask myself what I can do to reduce class size: 

  • Is the class doing too much?
  • Is there a responsibility that I could extract into another class? 
  • Is there something that doesn’t belong or need to be in this class? 

Sometimes no good answer presents itself right away—in that case, I leave the class as is. When there is a chance to refactor and reduce class size, I often take it.

 

Why are smaller classes better?

Easier to understand—Smaller classes do less. Things that do less are easier to understand. 

Would you prefer to read 200 lines of code or 2,000 lines?

Easier to change—Larger classes combine many loosely related concepts or concerns. Over time, internal interlinkings between these concerns develop. Such couplings are problematic—a change to a large class can trigger a cascade of additional modifications. A focussed, small class concerned with a single responsibility won’t have this problem. 

Would you rather make a change in a helper method that is called five or 50 times? 

Easier to reuse—Smaller classes are more likely to be reusable since their purpose is highly focussed. Huge classes that are ill-conceived and have methods combining multiple inseparable concerns are less likely to be reusable. Why? Because the code is so specific that it is only helpful in one scenario. 

Would you prefer to reuse (with little effort) or code it up from scratch (involving more energy)?

 

I recommend writing small, well-named, single-responsibility classes. 

 

Further Reading: 

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply