Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

language agnostic - How to find a similar code fragment?

Does anyone has some tool or some recommended practice how to find a piece of code which is similar to some other code?

Often I write a function or a code fragment and I remember I have already written something like that before, and I would like to reuse previous implementation, however using plain text search does not reveal anything, as I did not use the variable names which would be exactly the same.

Having similar code fragments leads to unnecessary code duplication, however with a large code base it is impossible to keep all code in memory. Are there any tools which would perform some analysis of the code and marked fragments or functions which are "similar" in terms of functionality?

Consider following examples:

  float xDistance = 0, zDistance = 0;
  if (camPos.X()<xgMin) xDistance = xgMin-camPos.X();
  if (camPos.X()>xgMax) xDistance = camPos.X()-xgMax;
  if (camPos.Z()<zgMin) zDistance = zgMin-camPos.Z();
  if (camPos.Z()>zgMax) zDistance = camPos.Z()-zgMax;
  float dist = sqrt(xDistance*xDistance+zDistance*zDistance);

and

  float distX = 0, distZ = 0;
  if (cPos.X()<xgMin) distX = xgMin-cPos.X();
  if (cPos.X()>xgMax) distX = cPos.X()-xgMax;
  if (cPos.Z()<zgMin) distZ = zgMin-cPos.Z();
  if (cPos.Z()>zgMax) distZ = cPos.Z()-zgMax;
  float dist = sqrt(distX*distX +distZ*distZ);

It seems to me this has been already asked and answered several times:

https://stackoverflow.com/questions/204177/what-tool-to-find-code-duplicates-in-c-projects

How to detect code duplication during development?

I suggest closing as duplicate here.


Actually I think it is a more general search problem, like: How do I search if the question was already asked on StackOverflow?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use Simian. It is a tool that detects duplicate code in Java, C#, C++, XML, and many more (even plain txt files). It even integrates nicely in a tool like CruiseControl.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...