In Visual Studio, with or without an extension, is there a way to automatically sort private methods inside a class based on the order of their usage (their location in the call stack)?
For example consider the following class:
public class MyClass { public void MyMethod() { TestC(); } private void TestA() { TestB(); } private void TestB() { Console.WriteLine("Hello"); } private void TestC() { TestA(); } }
The public method in this class is MyMethod
, it calls TestC
which calls TestA
which calls TestB
. I would like to (automatically) order these methods by this order so that the class looks like this:
public class MyClass { public void MyMethod() { TestC(); } private void TestC() { TestA(); } private void TestA() { TestB(); } private void TestB() { Console.WriteLine("Hello"); } }
I need to be able to select a class, request such method sorting, and have the methods sorted automatically. I.e., I don't want to manually sort these methods.
I understand that there are some nuances. For example, there could be a private method that is called from two methods which are at two different levels in the call stack. I guess in this case it makes sense to consider the smallest (call stack) distance from the public method.
UPDATE:
This idea of sorting the methods in this way comes from the Clean Code book by Robert C. Martin. In chapter 3, the Stepdown rule is defined which talks about having the higher level functions appear before the low level functions.
Doing a quick search for stepdown rule on google, I found a netbeans plugin at: http://plugins.netbeans.org/plugin/58863/stepdownruleplugin
I would guess that it does something similar to what I need, but for netbeans.
The keyboard shortcut is Ctrl + Shift + E .
So that would be in the following order : Constants, private members, public members.
Member variables at the top of the class, then constructors, then all other methods. And you order the methods to be close together with how they are used within the class (rather than arbitrarily putting all public then private then protected).
The ReSharper Plugin "Greenkeeper" does the job:
https://bitbucket.org/denniskniep/greenkeeper
The plugin can sort the methods in "newspapermode": Important code first and details at the bottom. The newspapermode has the same behaviour as the "Stepdown rule".
https://bitbucket.org/denniskniep/greenkeeper/wiki/SortingDeclarations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With