Duplicate code spanning multiple partial code blocks is not useful

Using Kotlin+Compose with gradle SonarCube plugin 3.4.0.2513 on CircleCI Android 2.1.2 orb, for a Bitbucket repository.

SonarCloud reports duplicate code, and we have multiple occurrences of it reporting a section which starts in one conditional block, spans linear code, and end in another conditional block.

This is not useful since code cannot be extracted from the end of one conditional and the beginning of another to make a new unique (non-duplicated) function, as least not without a lot of redesign of the logic and code which would be more disruptive than leaving it.

Duplicate code blocks should only be identified when the lines span a single context (but can include complete contents within).

Example screengrab attached.

Hello @CWolf ,

I think you may be misinterpreting the feature and putting wrong expectations on it.

The feature tells you which blocks of code are duplicated, not which pieces of code you should refactor into a function.

In face of a duplicated piece of code, factoring into a single function is only one option.

You could as well factor into multiple ones, realized this code is dead and remove, that the other block should be used instead and just replace with an existing function call, introduce a hierarchy of class or encapsulate a new class (or several) to provide the logic, etc.

It all depends on the context and the choice of the best solution is up to the developer.

So, duplication is best considered as a (very strong) hint to change and improve your code.

It’s only a small snippet and I don’t know your code.
Yet, for the sole sake of providing an exemple of the variety of ways code duplication can be addressed, I can try a guess and say that what’s duplicated is not a piece of code, but several pieces of logic:

  • the creation of a couple of graphical elements (is it a header or something? maybe put that logic into a function)
  • the separation of any set of graphical elements with a Spacer of 16.dp: maybe that could be a function of its own and the change will go beyond the highlighted duplicated block

Hope that helps,

Cheers,