Coding Practice: Class Size

Coding Practice: What is the maximum number of lines of code for a class?
Looking at some popular projects on Sourceforge, the majority of classes have fewer than 200 lines of code, with the average class consisting of about 50 lines of code.  Much like function length, it comes down to adhering to the Single Responsibility Principle from SOLID which states that every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class.

Quote:
“Consider a module that compiles and prints a report. Such a module can be changed for two reasons. First, the content of the report can change. Second, the format of the report can change. These two things change for very different causes; one substantive, and one cosmetic. The single responsibility principle says that these two aspects of the problem are really two separate responsibilities, and should therefore be in separate classes or modules. It would be a bad design to couple two things that change for different reasons at different times.”
–            Robert Martin

Application:
You can test a class for single responsibility by examining that class for reasons to change.  A class should only have one and only one reason to change.  When you find this is not the case, you should look to refactor your class using design patterns and applying the SOLID principles.

References:
Agile   Software Development, Principles, Patterns, and Practices
Head First Design Patterns

About Chris VanHoose

Principal Software Architect at CT Lien Solutions
This entry was posted in Software Architecture and tagged , , . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.