What are your .NET code-refactoring best practices?
Refactoring Best Practice Rule No.1: Write some tests first!
Refactoring should make code easier to maintain, and ideally reduce coupling between components/classes.
Good candidates for refactoring are classes with high-coupling to other classes, and classes that do too much (breaking the Single Responsibility Principle)
Tools like ReSharper or Visual Studio's built-in tools are useful aids.
If you are using VB.NET then check out: Refactor! for Visual Basic 2008
- Your code should be more readable/understandable not less when you are done.
- Generally your methods should become shorter, not longer.
- Repetitive code should be moved into it's own method and reused.
Don't mix refactoring with adding or changing functionality of the application.
Refactor with a suite of tests to ensure you aren't breaking anything.
As vague as the quesion is, it is hard to give any good answer. But I suggest you read Martin Fowler's catalog of refactorings, it gives you an excellent starting point:
Usually writing tests is not the first thing you do, with legacy code most likely you'll not be able to write tests (dependencies on db, external libraries, statics, and so on)
Lean on the tools first, use automatic refactorings like 'Extract method' (Resharper and VS are your friends)
Working Effectively with Legacy Code by Michael Feathers is a very good book to learn how to break those dependencies.
For numeric algorithms and parsers PEX is a very useful tool to easily create characterization unit tests.
Save your source code in a sourcecontrol system .. and when the refactoring fails just reset the current branch. That way you can never do any harm ... except waste some time occasionally. It's pretty cool since you can just hack & slash away at your code without worrying it'll never work again.
Also, when it's easy to do it on a new branch, do so. You never know when a bug creeps up halfway your refactoring process and you have to roll out a patch quickly (based on the previous, stable version).
One suggestion, keep note of specific ways you want or need to refactor and stick them in a wiki or document someplace, because later down the road you might not have the luxury of time to spend rethinking what you were going to do to improve or otherwise overhaul the code.
I recommend actually reading the book. "Refactoring: Improving the Design of Existing Code", by Martin Fowler.