Method of code refactoring — Analysis of method refactoring

Time:2020-9-26

Method of code refactoring — Analysis of method refactoring

Intro

If you want to write good code, you need to be alert to the bad smell in the code. Today, I want to write an article to introduce how to analyze your method and whether refactoring is necessary

A method usually consists of three parts: input, output, method body. We analyze whether a method should consider refactoring from these three aspects

Input

Method input is the method parameters. Generally speaking, the parameters of a method can be controlled within 7 (for reference only, can be measured by yourself,SonarQubeThe default method has at most seven parameters). If you have too many method parameters, you may need to consider refactoring a method parameter. The usual way is to encapsulate an independent model, and the parameters are used as the model properties.

To give a common example, for example, an API for news listing may be very simple at first, and only one is neededlastId, acountTwo parameters, but with the increase of business requirements, many other parameters may be added. For example, the front-end provides a keyword for full-text retrieval, provides a sortby for sorting, matches according to news title, author name, classification, and filtering according to publishing time. Finally, there may be many parameters for this method

I usually add oneXxxRequestThen replace the method parameter with this model, and then specify[FromQuery]It’s OK. You can compare the difference before and after the modification. Is the latter way more refreshing

Task List(int lastId, int count, string title, string author, string keyword, int categoryId, string sortBy, DateTime? beginTime, DateTime? endTime)
Task List([FromQuery]NewsListQueryRequest request)

Output

Output is the return value of the method. Return the specific type as much as possible and avoid using it as much as possibleTupleThe return value of the method should have a clear meaning

Use specific model instead of tuple to return value, especially some public methods that need to be accessed externally should return specific types. Although C ා 7.2 starts to support named tuple, which is much more friendly than before, and supports specifying a name for tuple, this is only compiler level. In fact, it is still Item1, Item2, It is better to use a specific model

Body

Usually, a method is not too long. Once you saw a group of friends make complaints about more than 2000 rows in a group, such a method is simply a disaster. Don’t let one method be too long and keep the cube simple. Some general logic is implemented through Filter or AOP.

Sonar has a method for analyzing the complexity of a method, officially known asCognitive Complexity

A brief introduction to the codeif/switch/for/foreach/trycatch/whileThe complexity of the method will be increased. If one level of nesting occurs, the complexity will be increased by 1. The default complexity of a method in sonar cannot exceed 15

Here are a few simple examples:

The complexity of the following method is 3 and has three if (else) branches

void Method1(int num)
{
  if(num > 0)
  {
  } 
  else if(num <0)
  {
  } 
  else
  {
  }
}

The complexity of the following method is 3,foreachIt brings the complexity of 1,ifIt’s also the complexity of 1, but because of thisifIs nested inforeachInternal, one level of nesting increases the complexity by 1

void Method1(int[] nums)
{
  foreach(var num in nums)
  {
    if(num > 0)
    {
    }
  }
}

The complexity of the following method is increased by twocatchThis causes the complexity to increase by 2 to become 5

void Method1(int[] nums)
{
  try
  {
    foreach(var num in nums)
    {
      if(num > 0)
      {
      }
    }
  }
  catch(InvalidOperationException e)
  {
  }
  catch(Exception e)
  {
  }
}

For more examples, please refer to the official introduction: https://www.sonarsource.com/docs/CognitiveComplexity.pdf

Reduce Complexity

Previously, we introduced some complexity analysis. How can we effectively reduce the complexity of the method

  1. Method parameters should not be too many, too many parameters should be considered to reconstruct input parameters, usually a new model can be created to manage input parameters
  2. Method return value should not be used, and it should not be used as far as possibleTupleAs the return value
  3. Methods should not have too many lines. Use the new syntax to reduce the number of linesifJudgment, such as using a null propagator instead of a series ofiflist?.FirstOrDefault()?.Name, a ??="test"
  4. The same logic of multiple methods is handled by facet logic, such as in each methodtry...catchThen we can use a complex try… Catch aspect logic. If it is MVC / webapi, we can also use theExceptionFilterTo achieve
  5. Parameter verification uses Microsoft’s modelvalidator or or fluent validation to verify, and try to avoid using a large number ofifJudgment leads to an increase in complexity
  6. Review the code carefully to see if some logic is merged together to avoid multiple logicsifNested in the same traversal logic
  7. And more

More

In addition to our own initiative perception of the complexity of the method, we can also use some third-party static code analysis tools to analyze our code, so as to obtain some modification suggestions and ensure the high quality of the code.

Sonarqube is a tool that is widely used at present and can be easily integrated with CI. There is a sonarcloud website that provides cloud services, which can easily integrate static code analysis for your open source projects. If you are interested, you can have a look at it. The address is https://sonarcloud.io/ I used it beforecodacy, seems not very popular. Sonarqube is recommended

Reference

  • https://sonarcloud.io/
  • https://www.sonarsource.com/docs/CognitiveComplexity.pdf

Recommended Today

On the theoretical basis of SRE

What is SRE? When I first got into contact with SRE, many people thought that it was a post with full stack capability in Google and could solve many problems independently. After in-depth exploration, it is found that SRE can solve many problems, but there are too many problems. It is difficult for a post […]