Best practices for managing code duplication?
Code analyzers like Sonar provide a metric called "Code duplication". This metric is useful, since it shows when code needs to be factorized. Knowing that, what are the best pratices regarding this metric? For instance, in my projects, I ensure this metric doesn't go above 0.5% and if it does, refactors are made. Is this how it is managed in the real world? Are there some resources (books, websites) considered as a reference on this subject?
In all honesty, my experience is that there are no best practices anywhere, even in something like code duplication. There are only principles that work to guide practice, and practices that are good in some circumstances. You don't mention whether you're working with automation code or application code: depending on the automation method and tooling, it's quite possible for automated testing projects to have a lot more duplication than application code projects due to the nature of the tasks performed. Even in application code, circumstances arise where it's better to have duplicate or near-duplicate code than to refactor and isolate the duplication. Classic ASP websites come to mind (if only because I'm up to my eyeballs testing one where there is a LOT of dup or near dup code - and it's there for valid reasons), but I'm sure there are other examples. In addition, it's very common "in the wild" for duplicate code to be used for a hotfix with the intention of refactoring later - but there is never time to refactor. This is obviously a long way from ideal, but I find there are usually two guiding principles in conflict in this situation: DRY (Don't repeat yourself) is conflicting with "If it ain't broke, don't fix it" - and the latter often wins because in many larger, older applications it's simply not possible to unit test to a level that allows for confident refactoring (also, in my experience, users will treat some of the application's bugs as features and actively use them - which can cause much suffering when those bugs are fixed).