Code inspection: Extract common code
This inspection reports equivalent code in different branches of if
and switch
statements. The corresponding quick-fix helps you automatically extract the duplicated code and put it either before or after the branching.
If the equivalent code is intended, consolidating common statements makes your code cleaner and easier to maintain. However, this inspection can also be useful to catch bugs because often the equivalent code in branching constructs is the result of copy-pasting. So when you see this issue in your code, first check whether the equivalent code is intended.
void GreetCustomer(string name, bool known)
{
var sb = new StringBuilder();
if (known)
{
sb.AppendLine($"Hello, {name}!");
sb.AppendLine("Welcome back!");
}
else
{
sb.AppendLine($"Hello, {name}!");
sb.AppendLine("Welcome!");
}
Console.WriteLine(sb.ToString());
}
void GreetCustomer(string name, bool known)
{
var sb = new StringBuilder();
sb.AppendLine($"Hello, {name}!");
if (known)
{
sb.AppendLine("Welcome back!");
}
else
{
sb.AppendLine("Welcome!");
}
Console.WriteLine(sb.ToString());
}
Last modified: 26 July 2024