Way to check redundant code in C# [duplicate] - c#

This question already has an answer here:
Detect duplicate code in Visual Studio 2010
(1 answer)
Closed 5 years ago.
Is there any tool or way I can check how can I optimize my code? removing redundancy? I am using VS 2010
Thanx

I don't know about removing redundancy, but ReSharper has some nice code analysis features that can help to identify unused code blocks. It can also make suggestions for cleaner code, but it's not always 100% accurate.

Such tools, even if they existed, wouldn't be reliable. The best would be to perform a code review by a good developer or architect.

No tool can replace experience and expertise. There are a number of productivity tools that can help, a popular one being ReSharper for example, but it's not going to fix everything for you. At some point you just have to rely on your abilities and the abilities of your team members. Learning how to code well takes time.
It often helps to step back and look at your code with the mindset of certain design principles. S.O.L.I.D. can be a great place to start. Some other questions you can ask yourself are:
Are your classes and types properly encapsulated?
Is your code test-driven or behavior-driven in any way?
Do your tests define discrete unit of behavior, or are they just tailored to the implementation that's being tested?
To specifically address redundancy, quite simply, do you have copied/pasted code doing the same thing in two places?

A profiler will give you a good idea of where your application spends most of its time. From knowing what to how to optimize, though, requires experience as well as knowledge of both the code base in general and the problem domain.

What you want is Code Coverage tools. These keep a record of which lines of code are executing. In order for this to be effective, a complete test suite, or manual test run, is required. This will show up the lines of code that are never used, and will help you make decisions.
Static analysis can also help you with code paths and give you information about how and where your code is called.
A couple of good question sabout code coverage:
What can I use for good quality Code Coverage for C#/.NET?
C# Code Coverage metrics
Also look at Microsoft's FxCop for static analysis:
http://msdn.microsoft.com/en-us/library/bb429476(VS.80).aspx

There is http://clonedetectivevs.codeplex.com/ which is a VS plugin. It uses http://conqat.cs.tum.edu/ under the hood. I've not really used it but does what you asked. Couple that with code reviews and might help.

There is a (commercial, 249€) solution checking for duplicate code, even in large projects.
http://www.solidsourceit.com/products/SolidSDD-code-duplication-cloning-analysis.html

For that purpose we use the build-in Duplicated Finder in our TeamCity build server.

Related

StyleCop for ReSharper

I like stylecop and we use it to enforce coding standards.
I dont like the fact that there is no way to automatically fix problems. So was thinking of making a plugin. Once I realised that 2010 is better for doing this I backtracked.
I've been looking for an existing tool to help automate this process and have come across stylecop for resharper. http://stylecopforresharper.codeplex.com/
Has anyone got any positive/negative experiences of using this plugin
I use it for about a year now, and I found it to be quite stable. It slows down things a little bit (like every plugin naturally does), and it can be somewhat annoying, if almost everything is underlined during typing, but generally speaking, I found it to be a valuable coding help...
I have used the StyleCop for Resharper to very good effect. Coupled with the clean code feature of Resharper it helps in organizing the code and improve the quality by enforcing the standards.
If you are serious about improving the quality of code, I would suggest making StyleCop for Resharper a part of your daily life.

Taking over someone else's code

I am taking over someone elses code. What are some good ways to learn what that programmer did as quickly as possible? I have been running it, stepping through it and looking at the callstack. What else can I do?
Sorry I forgot to mention, but there is little documentation and I have been trying to fix simple problems. Thanks!
Set logging to observe in what sequence things are happening.
Read here: Hired as a developer to maintain and update current code base, no docs!
Start writing unit tests, as that will get you using his classes/methods, and you will do two things, learn it, and either find bugs or have tools ready in case bugs appear.
Usually the best way is to start working on the code fixing small bugs. The more true time you spend with it is the only way to learn the code base. There is no magic way to learn a code base. It will take weeks, months or possibly years depending on the complexity. However for most generic business systems a ramp up time is about 6 months of code knowledge and 6 months separate of industry knowledge to truly understand it all.
Fix a simple problem in it.
Edit:
Then fix bigger problems, and start writing documentation and unit tests, of the areas you understand. Build on those areas, and one day you might understand the whole system.
Documentation? Reading the code itself, without running in the debugger?
Other than that, you're doing what I would do.
There's no silver bullet in how can you understand someone else's code quickly. Specially if it's full of hacks and no documentation is avaiable.
You should try to understand the class structure, and execute the normal flow of the software, with a debugger help.
Don't jump too much code sections "oh, I think I know what this section does". No, you don't. You would be surprised of what "innovation" we may find in code.
Logging is good to see what the code does.
If you have a versioning system you could go and see what changes di the programmer do to what pieces of code, browse some history.
I find it useful sometimes to somehow try to understand the programmers code style, this helps me understand how could he think about a problem and solve it.
The first thing I'd do is take a look at the simplest dialog box and its code, mostly to analyze the coding style and look at how the developer prefers to arrange the code.
Once you know the coding style, and roughly where everything will exist in the file (or if things are put in randomly -- even that is helpful to know), it will be easier to go through everything else.
Talk to the users of the other person's code if you can (either end-users or other developers that had to work with his code). That will give you a sense of the quality of the other persons code - was it released with just a few bugs or did it take 6 months of revisions to get it right? Was the developer careful about making a nicely polished application or was it a mess? That should give you some idea of whether you need to just tune-up the code a bit or start replacing large chunks of it.
I like starting to add tests to the methods of the code, if they are not already there. Figuring out how to cover the code gives you a lot of insight into the codepaths, what the expected output should be, etc...
Everything everyone else has said is accurate in learning what the coder has done.
One other way of looking at it though is to learn the program itself. Play with the application in depth like a user would and understand what the program itself does. Once you understand the final system thoroughly it will be a lot easier to work out how and why it was written.
The first place I start is the database.
In my experience, understanding the datamodel is key to giving you context when you go through the code. (this assumes the data model is not a generic key-value generic entity table)
I find that I wont learn the code completely until I start fixing bugs / modifying it. If the original programmer is still there, then discussing the changes before implementing them would help.
It wouldn't hurt to document what you learn about classes, functions, etc. as well, just so the next guy (or another person who gets hired to work on the same stuff).
Also, when I've done this before, I've found it best to use the program quite a bit before trying to understand the code. May sound obvious, but more of what you see will make sense after that. Unit testing, as other people have suggested, may also help in the same way. (Helpful when you feel confident enough to refactor, as well.)
One thing that helps me learn systems faster is writing the documentation myself.
I get a overview
I will see many bugs/bad design decisions. Which makes it easier to order and prio them. (instead of picking a irrelevant bug and solving it, I will fix those that really matters)
I later on have an documentation.
Documentation will make it easier to justify refactoring/rewrite to the suit's
I think knowing what the code does, the problem it was written to solve at an high level is a good start. With that one can then mentally, at an high level too try to envision how such a problem might be solved with the type tool used.
From then, looking through the code will take on some meaning, and it will help in making it possible to follow the thought of the original developer. In addition, you will quickly spot when you are getting lost.
I also believe the code should document itself as my experience most time is a documentation outside of the code most times is out of sync with the code and could be misleading. So a few comments here and there, class headers, method comment should help too.
First time I inherit another person's code, I had migraine after two days, i was a nightmare.
So have fun.
I've spent most of the last year working on code that I inherited from someone else. There was no documentation and a large amount of what the system was meant to do was not written down anywhere, but in the clients head. The key for me has been to ask as many questions as I could and gather information from every source available. I would recommend compiling your own documentation as you go.
Many people might say don't rewrite code, but that may often be the best way if the code is poorly commented or coded (not self documenting). For code that I struggled with it has often been the best solution.
Another helpful thing to have is some kind of standards document before you begin. The standards doc will help you decipher the code or bring code up to spec and make it easier to understand.

Redundant Code Checking

Are there any tools that can find any private functions without any references? (Redundant functions)
Reason being, that a function may have been created and called from a couple of areas, but as the project expands and grows, these two calls may have been removed and swapped with a better alternative. But the method may still remain. I was wondering if there were any handy tools that would look through the code, spotting private functions and checking if they have any references, if not, inform the user of the situation.
It wouldn't be too tricky to create one myself, but I was wondering if there were any accessible apps that could do this with the files containing the code?
My code is in c#, but I can imagine that this question covers a variety of coding languages.
ReSharper does the job.
If your code has Unit Tests (it does, right? ;-) then running NCover will allow you to identify methods that aren't being called from anywhere. If you haven't got any unit tests then it's a good excuse to use for starting to build them.
In the general case, I'd suspect that code coverage tools are a good fit in most languages.
Eclipse does it automatically for Java, not sure if you can have same thing for C#.
Another question might even be "Does the c# compiler remove private methods that aren't actually used?".
My guess would be no, but you never know!
EDIT:
Actually, I think it might be hard to tell where a method is used. It might be private, but it can still be used as Event Handlers. Not impossible to check, but I'm sure that aspect would make it a little more difficult.

C# code analysis - VS 2005

I have a C# user control project which causes intermittent .NET run time error, a generic error, and wondering if there is any code analysis tool that I can point at my .sln file which would tell me what may be causing my error
Is there a tool that will tell you what you're doing wrong?
No. That's part of the fun of programming. It's impossible for a computer program to look at a piece of code and definitively determine what all of the errors are.
Are there tools out there that can tell me some things my program is doing wrong?
Yes, these are called static analysis tools. FxCop is a free tool available from Microsoft that will an amazing amount of static analysis on your code base.
I'm not 100% sure if the standalone version can be pointed at a .sln file. But it can easily be pointed at the build output from a solution.
http://msdn.microsoft.com/en-us/library/bb429476.aspx
What you need is a Static Code Analysis tool - Besides FXCop which JaredPar mentioned there are others.
Another option I have found recently which gives a useful way of finding issues like this is PEX which does white box unit testing. So when you run the PEX explorations it will attempt to send a lot of values at your methods via it's autogenerated unit tests which may help find odd issues caused by strange/unexpected data.
But I would not confuse static analysis tool with a debugger, and I believe what you need here is debugging. In other words, FxCop might tell you that everything's great, but you can still get a run time exception.
Some errors in run-time can be really difficult to spot simply by looking at the code (race conditions with multiple threads, for example). So there is no "code analysis tool" that could a run-time exception simply by analyzing the code.
Check this link for some examples on debugging: http://msdn.microsoft.com/en-us/library/ms954594.aspx. You will have probably have to do some stepping through your code using a debugger, maybe Trace some data to a log file, and then try to find exactly where it goes wrong.
As far as tools go FX Cop is really good for doing Code Analysis and it's free but something else to look at is http://www.jetbrains.com/resharper/ for doing on the fly code Analysis and it promotes good development practices.
But these may be the wrong tools for the job and may not solve the problem your having, the code may be syntactically correct but there is a logic error that is causing your problem it's like a spellchecker, all words my be spelled correct "Evert bird is conical" means something completely different than "Every word is correct".
Your probably going to need to spend some time in the debugger or using some form of trace tool like dotTrace Profiler there are a couple more out on Visual Studio Gallery like http://www.debuginspector.com/
NDepend is fully integrated in VS2005, VS2008 and VS2010. So you can simply point NDepend to the sln that you wish to analyze, and NDepend will build a full report for you.
In a few clicks, you can visualize which types depends on which types, etc. This will obviously not magically solve all your problems, but that is likely to put you on the right track.

How do I find and remove unused classes to cleanup my code?

Is there a quick way to detect classes in my application that are never used? I have just taken over a project and I am trying to do some cleanup.
I do have ReSharper if that helps.
I don't recommend deleting old code on a new-to-you project. That's really asking for trouble. In the best case, it might tidy things up for you, but isn't likely to help the compiler or your customer much. In all but the best case, something will break.
That said, I realize it doesn't really answer your question. For that, I point you to this related question:
Is there a custom FxCop rule that will detect unused PUBLIC methods?
NDepend
Resharper 4.5 (4.0 merely detects unused private members)
Build your own code quality unit-tests with Mono.Cecil (some samples could be found in the Lokad.Quality the this open source project)
Review the code carefully before you do this. Check for any uses of reflection, as classes can be loaded and methods can be dynamically invoked at runtime without knowing at compile time which ones they are.
It seems that this is one of the features proposed features for the next version of Resharper. That doesn't help yet, but hopefully the EAP is just around the corner.
Be careful with this - it is possible that you may remove things that are not needed in the immediate vicinity of the code you are working on but you run the risk of deleting interface members that other applications may rely on without your knowledge.

Categories