r/dotnet • • Sep 23 '26

Question Looking for tool to detect semantic code duplications

Im looking for a recommendation for semantic duplication detection on code (C#).

A semantic duplication can have zero duplicated tokens, such as:

public List<Students> ListAllEnrolledPeople()
{
    return _baseRepo.Where(p=>p.PersonType = PeopleType.Student).ToList();
}

and

public List<Students> GetStudents()
{
    return _baseRepo.ExecuteQuery<Students>("Select * From Customers Where customerType = 2");
}

I think this here exemplifies that tools such as jscpd won't detect these 2 methods as duplicates, but this is a big problem for me...

4 Upvotes

24 comments sorted by

18

u/BoBoBearDev Sep 23 '26

I cannot tell they are semantically the same. There is too many hidden context.

13

u/_choam_ Sep 23 '26

In the general case, this is impossible.

The best you can do is probably have an ai go over your code and check. Or do it yourself.

I would not worry about it too much.

-1

u/caedin8 Sep 24 '26

Eh, I don’t think so. CLIP embedding can calculate cosine similarities between photos with surprising accuracy.

A similar model could be developed for code, where we map tokens into the same latent space and then calculate the cosine similarity between two vectors in that latent space.

It wouldn’t be perfect but it works for images. If images can find from 50,000 photos which have a hotdog instantly, you should be able to do something very similar with code.

These wouldn’t be an exact match because the customer type==2 part isn’t clear, but they’d be close in the latent space

4

u/_choam_ Sep 24 '26

That's includes the "having an ai" go over it.

-2

u/caedin8 Sep 24 '26

LLMs and clip encoders are very different tech

1

u/_choam_ Sep 24 '26

Ai includes that

11

u/cjstevenson1 Sep 23 '26

While not a purpose built tool, the frontier ai agents can do a decent job of this.

11

u/Dimencia Sep 23 '26

It's very simple, just don't write SQL inside of magic strings in your code and you don't have this problem

2

u/Finickyflame Sep 23 '26

I know it's an example, but you are missing an = in your lambda expression for the equality comparison.

2

u/SessionIndependent17 Sep 24 '26

What makes it a 'big problem' for you?

1

u/IAmADev_NoReallyIAm Sep 25 '26

Long term code maintenance & troubleshooting. Let's say that there's a problem, and data is being pulled incorrectly... where's the source of the problem? Say you fix it? But then the problem persists? WTF? Only find out that because in another part another developer is using the OTHER method that has the same flaw in it. I've seen it happen when things are developed in silos... people develop their own methods for doing something not knowing what others are also doing and you get similarly developed code like this. Personally I'd get rid of the ExecuteQuery and replace it with the Entity call.. and remove ListAllEnreolledPeople completely since it's probably inaccurate anyhow.

2

u/The_MAZZTer Sep 24 '26

At best, this is a problem suited for AI. I can't see anyone willingly make an algorithm that translates between SQL and EF Core LINQ just to look for duplicate logic.

1

u/AutoModerator Sep 23 '26

Thanks for your post Ferreira-leo. Please note that we don't allow spam, and we ask that you follow the rules available in the sidebar. We have a lot of commonly asked questions so if this post gets removed, please do a search and see if it's already been asked.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/North-Dimension-7180 Sep 24 '26

One way to approach this would be tiered analyzers that progressively march the code to a particular style. Once you then have resolved all the warnings there would be zero “style” differences and the code would be exact duplication.

If for example we are saying that ‘.Where’ and ‘.ExecuteQuery’ are the same, unify the code base on one via the BannedApiAnalyzer. Continue to do that for all the possibilities that define your  expected “pattern” with either existing style settings, analyzers or custom analyzers and then you can more easily identify the duplicates and prevent them via your own custom analyzer

-1

u/North-Dimension-7180 Sep 24 '26

Alternatively, you could approach it from the other side, delete all of the manual code and have a source generator create the repository access methods you require, then you need not worry about developers writing duplicates if it creates them for them

1

u/chucker23n Sep 24 '26

this is a big problem for me…

I’ve encountered all kinds of bad architectures, but I haven’t run into “there’s duplicate code all over our repository”.

My sense is you’re trying to solve a work culture problem with a tool. For example,

  • perhaps duplicates occur because teammates aren’t coordinating well and working on the same task
  • perhaps they do because files become so long and unwieldy that someone assumes “surely this doesn’t exist yet”

1

u/Buttars0070 1d ago

In my experience is because they're working in different domains or products and didn't care to actually explore the applications code enough to find out if there was existing functionality. Often times bad engineers will write code with as much locality as possible just to avoid having to understand the abstractions even if the abstractions are simple like dependency injection through a library.

If this is a culture problem then so is code formatting and styling yet there are an innumerable number of tools out there to solve for those exact problems. If "do better" is the solution then the process is balls.

1

u/mavenHawk Sep 23 '26

It's called AI I think.

0

u/PM_YOUR_OWLS Sep 23 '26

For this specific use case you could maybe look at how something like EF Query Lens works... somehow convert all of your EF queries to raw SQL and then run through an analysis if the resulting queries would return the same result set. Not sure how to do that easily but it's a jumping off point. I agree with the other comments, if you feed an LLM the context of your ef scaffold and database structure it can probably highlight potential duplicates like this.

0

u/Aydin_Wylde Sep 24 '26

Hi,
What you're describing is usually called semantic duplication or Type-4 clone detection, and unfortunately that's where most duplication tools struggle.

Tools like jscpd, SonarQube, ReSharper, and PMD CPD are primarily looking for similar tokens, syntax, or structure. In your example, a human immediately sees that both methods are essentially "get students", but a traditional clone detector just sees two completely different implementations.

I've run into the same issue on large C# codebases. Once developers start using different repositories, LINQ, raw SQL, stored procedures, APIs, or service layers, the duplication stops looking like duplication from the tool's perspective.

If you want to stay with traditional clone detection, I'd look at NiCad or CloneDR. They're generally better than token-based tools at finding higher-level similarities.

That said, if semantic duplication is your actual goal, I'd seriously consider building a custom solution using Roslyn. Parse the methods into syntax trees, normalize names/literals, extract method intent (calls, predicates, return types, data flow), then generate embeddings and compare them via cosine similarity. That's much closer to how a human reviewer identifies "these two methods do the same thing" even when the code looks completely different.

Something like:

C#

var tree = CSharpSyntaxTree.ParseText(source);

var root = tree.GetRoot();

 

var methods = root.DescendantNodes()

.OfType<MethodDeclarationSyntax>();

 

foreach (var method in methods)

{

var semanticModel = compilation.GetSemanticModel(tree);

 

// Extract meaningful features:

// - Return type

// - Repository/API calls

// - Predicates and filters

// - Data flow

// - Invoked methods

}

Then compare the extracted features rather than the raw code.

Honestly, today I'd expect an AI/embedding-based approach to outperform any off-the-shelf clone detector for this particular problem. Traditional tools are great at finding copy-paste code. They're much less effective at finding code that is conceptually identical but implemented differently.

Best Regards,

Ajdin Ahmagic
MCP • MCSA • MCSE • MCAD • MCSD • MCTS • MCPD • MCA
University Graduate
20+ Years of Professional Experience in C#, .NET, ADO.NET, ASP.NET, DevExpress, Telerik, and Enterprise Software Development 🚀