The key idea is not short methods nor few methods per class. The key idea is Conceptual Singularity. The class has one and only one purpose. All methods support a single, singular purpose and nothing else.
When a class is singular, it tends to be “small” simply because every line you add potentially disrupts the Conceptual Singularity of the class. A “small” class tends to have fewer methods, again, simply because every method you add increases the probability of contaminating the singular purpose. Methods tend to be short for the same reason.
- Easier to test.
- Easier to reuse.
- Easier to modify.
- Less bugs are discovered on short methods and on short classes.
- Development team codes faster, because there is less need for refactoring.
Take a relatively small class and go merciless on it. Refactor it as much as you possibly can. When you’re done, look at any class that has multiple member variables in it. Can any one of the member variables exist separately from the others? Split off that member variable into it’s own class (even it seems absurd to you). Can the methods be partitioned into methods that work on variable A and methods that work on variable B? Split the sets of methods into two classes. Can any part of the class be made more abstract? Extract out the abstract part into a new class. Continue doing this until you can’t refactor any more. Split the class up based on the functionality. When you’re done, you will have singular purposes classes. Repeat this experiment over and over again. After two years go back and take another look at your first attempt. Split the classes up even further on what you now see.
PHP_CodeSniffer is a library that tokenises and “sniffs” PHP code to detect violations of a defined set of coding standards. It is an essential development tool that ensures that your code remains clean and consistent. It can even help prevent some common semantic errors made by developers. Raphael Stolt did a great job porting the TooManyMethods and ExcessiveMethodLength rules to PHP_CodeSniffer. Visit his blog for more information.