PHPMD: TooManyPublicMethods and allow-underscores

Earlier this month, PHPMD 2.3 was released. It contains several new features, including two that I added primarily for use in Wikibase, the software behind Wikidata. For a more general post on PHPMD and style checks in PHP, see PHPCS and PHPMD: my experiences.

New rule: TooManyPublicMethods

When I first tried out PHPMD, I found that I had to either disable its TooManyMethods rule, or increase the limit significantly. The reason being that when you have your methods do only one thing, you can easily end up with many private methods. And while having 15 private methods is not suspicious, especially if they are small, having as many public methods (excluding getters and setters of course) is definitely a smell. The new TooManyPublicMethods rule added in 2.3 now allows setting different limits for public and non-public methods. This release also changed the default limit of TooMnyMethods from 10 to 25, to avoid encouraging people to not properly split their methods.

Support for underscores in test methods

In the Wikibase codebase, we use cameCaseMethodsNames in our production code. For this the CamelCaseMethodName rule is great. In our tests we also follow this naming pattern, with one exception, we allow a single underscore when writing test methods such as testGivenNegativeValue_setAwesomenessThrowsException. The underscore separates the “given” and the “then” parts of the specification. The CamelCaseMethodName rule already had a allow-underscore option that we could have used here. It is however not ideal for our use case, as it would allow underscores in non-test methods, and not restrict the location of the underscore, or indeed, the number of underscores.

PHPMD 2.3 adds a new “allow-underscore-test” option to the CamelCaseMethodName rule, which allows for a single underscore in methods that start with “test”.

Of course, this is still rather permissive. The naming convention I follow is much stricter: there need to be at least two words between “test” and the first undesrcore and at least two words after the underscore. Plus the first word after the underscore must start with a lowercase letter. You cannot restrict this yet with any released version of PHPMD, though I haveĀ  new TestMethodName rule submitted as a pull request.

 

Leave a Reply

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