If I have a large .NET method, I want to know if it is good practice to split it up into multiple methods or not. My concerns are:
1 – Is there any point creating a method if it will only be called once?
2 – If I’m calling a private method from within my class, I try not to use instance variables. Is this good or bad practice? For example:
var a, b;
public void TestMe
{
FirstTest(a,b);
}
private void FirstTest(paramA, paramB)
{
//code here with passed in parameters
}
//instead of:
private void FirstTest()
{
//code here with instance variables a,b
}
edit: replace global with instance
Yes, there are many reasons to do this. Readability is perhaps the most important. If you can make a method more readable and maintainable by breaking it apart, then by all means do so.
In my experience with refactoring legacy code where a method is way too long, there are little pieces of code that appear over and over again. These are usually the best places to look for refactoring opportunities. Creating separate methods for those pieces can greatly decrease a method’s length, and, thereby, greating increase its readability.
Usually, the smaller you can make a variable’s scope the better. Like you, I tend to use parameters whenever possible. If a method has references only to its own parameters, then it becomes much easier to reason about the method, verify its correctness, and use it correctly. (And if a method can do this and not modify any state, then that buys you a lot of maintenance benefits.)
If the purpose of a method is best served by manipulating an object’s fields, then that is perfectly acceptable, and in many cases, unaviodable. But, as you indicate, this is especially true with public methods. When refactoring a large method into smaller ones, I will rarely, if ever, access member fields directly in the new methods. This is mainly just to make it easer to reason about the program’s behavior.
When refactoring in this manner, make sure you mark the new methods as
staticif they don’t access any fields. This will make the intent explicit.