We deployed this new code rating algorithm already a bit over a week ago. In this blog post, we would like to share the changes and the reasoning behind them with you.
So far, class ratings were weighted averages of their methods’ ratings. Some of you have asked for more detailed assessments of classes which better cover things like coupling and cohesion for example. To measure these characteristics reliably however, you need to have type information of the code. With the introduction of the new PHP Analyzer version, that type information is readily available and we can compute these metrics for you.
So, instead of just making class ratings averages of methods, they now have their own criteria which include:
In the cohesion analysis, we compute the number of un-connected components which you have in your class, a component basically represents a concern. So ideally, you would want to have exactly one component in your class.
Two methods are considered connected if either a method calls another method or if they access the same property. This is also called data cohesion, and works very well if your data resides in the same class like its behavior (which is one of the benefits of object-oriented programming).
As there are some exceptions to this rule like utility classes or simple getter/setter transport objects, PHP Analyzer has heuristics to detect these types of classes and will ignore such methods. Also, PHP Analyzer ignores connections between components which are created through cross-cutting concerns like logging for example. For more information, you can also check out the documentation.
The results of this analysis are also available as a graph which helps you for example if a class gets too big and you would like to split off one of the weakly connected components. The graph below for example shows a focused class with a single concern:
In the coupling analysis, we basically count the number of other types (like interfaces, classes) that your code depends on. This is an indication for how robust your class is to changes in other classes.
PHP Analyzer uses some heuristics to determine the stability of code. For example, it does not count any types defined by the PHP runtime, or also types and methods which are annotated with the @api annotation as these dependencies should rarely - if at all - change during the lifetime of a project.
Try it out and let us know what you think.