Refactoring C-sharp code with ReSharper
In software engineering, the term refactoring means modifying source code without changing its external behavior, and is sometimes informally referred to as “cleaning it up”. In extreme programming and other agile methodologies refactoring is an integral part of the software development cycle: developers alternate between adding new tests and functionality and refactoring the code to improve its internal consistency and clarity. Automated unit testing ensures that refactoring does not make the code stop working.
Refactoring does not fix bugs or add new functionality. Rather it is designed to improve the understandability of the code or change its structure and design, and remove dead code, to make it easier for human maintenance in the future. In particular, adding new behavior to a program might be difficult with the program’s given structure, so a developer might refactor it first to make it easy, and then add the new behavior.
An example of a trivial refactoring is to change a variable name into something more meaningful, such as from a single letter ‘i’ to ‘interestRate’. A more complex refactoring is to turn the code within an if block into a subroutine. An even more complex refactoring is to replace an if conditional with polymorphism. While “cleaning up” code has happened for decades, the key insight in refactoring is to intentionally “clean up” code separately from adding new functionality, using a known catalogue of common useful refactoring methods, and then separately testing the code (knowing that any behavioral changes indicate a bug). The new aspect is explicitly wanting to improve an existing design without altering its intent or behavior.
Refactoring is a useful technique that’s easily done manually. However tools can help refactoring go much faster.
There’s alot refactoring tools in Java world, but for .NET/C# I recommend ReSharper. As well as refactoring it also brings many other features from the popular Java IntelliJ IDE to the the C# world. ReSharper’s 17 automated refactoring support takes care of code consistency and compilability after even the most dramatic modifications. ReSharper supports the following types of refactoring:
- Rename symbol with reference correction
- Move type to another namespace with reference correction
- Move type declaration to a separate file
- Change method signature (add/remove/reorder parameters, change parameter type or return type)
- Extract method
- Introduce variable
- Inline variable
- Convert method to property
- Convert property to method(s)
- and more …