DEV Community

Cover image for Pitfalls of static code analysis: class, function, or method length rules
Kirill Artamonov
Kirill Artamonov

Posted on

Pitfalls of static code analysis: class, function, or method length rules

Lack of code quality is a re-occurring problem in many software projects, teams, and organizations. Static code analysis with a set of simple rules seems like a good solution to the problem.

There are some pitfalls of static code analysis, and I wanted to share my thoughts about one of the rules: class, function, or method length restrictions.

The rule

Whenever there's a lengthy fragment of code, there's a problem with it. Most certainly it violates the single-responsibility principle, it is hard to understand and troublesome to update.

A rule that enforces a hard limit of X lines per code block is a seemingly simple and effective solution. However, it introduces behavior that I would call mechanical refactoring.

Mechanical vs. insightful

Mechanical refactorings are happening when something external is enforcing it: e.g., when a certain number of lines is reached and the commit or merge is blocked. They are happening not when talking to domain experts, or when there are new insights arising from working with the code, or when new abstractions are being discovered. To contrast the two types of refactoring, I'd call the latter insightful refactorings.

Mechanical refactorings require the answer here and now, insightful ones can grow and ripen in people's heads for days or even weeks. The quality of a mechanical refactoring is thus often less than of an insightful one. A quick low-quality mechanical refactoring today might also obstruct the view or make an insightful refactoring harder next time.

What to do?

If you think there's a problem with the software quality of your product, I'd advise focusing on the people, not on the tools like ones for static code analysis.

Get your team members excited about clean code, give them time and space to think about the code and the domain, give them time and space to practice writing cleaner code, to experiment with it.

That's it, happy coding!

Top comments (0)