This article will talk about:
- How to restructure your code
- How to deduce your code length
- How to overcome complexities
There is a one solution to all these problems, Code Refactoring.
I'll explain how to do refactoring more easily using Visual Studio. You can use any version.
What Refactoring is
In simple words it can be explained as the process of improving your code after it has been written by changing:
- The internal structure of the code.
- External behavior of the code.
Methods
There are 5 methods of applying effective refactoring over your code, these methods are already available in Visual studio:
- Extract Method
- Extract interface
- Rename
- Promote variable to the parameter
- Encapsulate Field
- Generate method stub
Extract Method
Extract method is the most simple and best way to refactor the code. It breaks your code into several small blocks or methods. You can apply this method in your code segment easily.
Extract Method | Procedure
Select any block of code from your code segment.
[This block of code can be any conditional statement like IF, can be a loop statement like for, can be a method or anything you need to be refactored within you code segment.]
Now after selecting this code segment you have two options, you can either use the Refactor option from the menu in Visual Studio or you simply right-click and select it. In both ways you will get to the same place.
Or try this:
// right-click option
After clicking on the Refactor option click on "Extract Method...".
On clicking, a pop-up window will appear.
[Since I am explaining all this as a reference of C#, you need to enter a NEW_METHOD name in the pop-up box window in the blank field.]
Now click on OK.
Then if there are any variables in you code segment then all those were automatically shown as variables in the method signature.
Once the name of the code is confirmed, the new method will be created automatically.
Now, a call to the new method replaces the extracted code block.
the next article in this series will be soon.
#HappyCoding