Refactoring: code, dates, application

Refactoring is a kind of reorganization. Technically, it comes from mathematics when an expression is put into equivalence - factors are cleaner ways of expressing the same statement. Code refactoring implies equivalence; the initial and final products must be functionally identical. In practice, it makes the code more clear and clean, simple and elegant. An example is the range from renaming a variable to introducing a method into a third-party class for which the developer does not have rights.

Analysis and refactoring to create clean code

It simply means improving the design of existing code without changing its observable behavior. Originally conceived in the Smalltalk community, it has now become a core development technology. Although refactoring tools make it very easy to apply. It is important that the developer understands why he is doing this and why it will help him, for example, in a situation where you need to allow the reuse of a repeating block of code.

clean code creation analysis and refactoring




Each refactoring is a simple process that makes one logical change in the structure of the code. If you change a large amount of code at a time, it is possible that errors have been entered. But when and where the errors were created is hard to say. If changes are made in small steps with checks performed after each step, an error probably occurs in the test run immediately after the code is entered into the system. By refactoring the code, one could check this step, and after canceling the step, it could be divided into even smaller steps to detect failures.





This is the advantage of comprehensive unit tests in the system, protected by extreme programming methods. They give developers and managers the confidence that refactoring has not broken the system, the code will behave the same as before.

The code improvement operation occurs in approximately the following stages:

Act

Questions to ask, actions

Problem detection

There is a problem? What is the problem?

Problem Description

Why do you need to change something? What are the benefits? Are there any risks?

Production

solutions

What should be the “target state” of the code? What code conversion converts the code to the desired state?

Code change

The steps that will refactor the code.

It is usually performed in small steps. After each such step, the developer usually remains in the working system, which does not functionally change. Practitioners alternate bug fixes and complement the code between these steps. Thus, refactoring does not exclude the possibility of changing functionality, it simply says that this is another activity related to reordering the code.

Continuous quality management process

Ideally, refactoring will be part of an ongoing process of quality improvement. In other words, it will be easily intertwined with other daily activities of each software developer.

Creating clean code with analysis and refactoring is useful when an error occurs and the problem needs to be fixed or the code needs to be expanded. The process, along with the maintenance or addition of new features, also allows managers and developers more likely to resolve problems, as this will not require an additional testing phase.

refactoring improvement of existing code




If it is difficult for the responsible developer to understand the code, he will ask questions and begin to document the incomprehensible part, which will be a good starting point for applying new methods. Often the schedule of the cleaning operation does not immediately make a good decision. It is possible that the function was added in a hurry and the error was not fixed. In these cases, the corresponding code should be marked with a FIXME note so that it can be recycled when time permits. Such circumstances require refactoring to improve existing code, not for individual elements, but for the whole project.





When it is time to solve the accumulated problems, they scan FIXME and TODO. Above the code base there will be all the problems for review. Then they can be reorganized into an appropriate priority. Refactoring is a good thing because complex expressions are usually built from simpler, more bulky components. It either provides these simpler components, or reduces them to a more efficient complex expression, depending on how the programmer is going to act.

For an example of the effectiveness of refactoring an existing code, we calculate the terms and operators: (x - 1) * (x + 1) = x 2 - 1. Four terms versus three. Three operators versus two. However, the left-hand side expression is easier to understand because it uses simpler operations. In addition, it provides more information about the structure of the function f (x) = x 2 - 1, since the roots are +/- 1, which would be difficult to determine simply by “looking” from the right side.

Action areas

Software for refactoring improvements to existing code is available on the network in small numbers, but most of it is well developed. Over time, the size of user software and its complexity increase, while errors increase, and therefore the reliability of the code decreases. Software developers, especially when they are not the original authors, are finding it increasingly difficult to maintain and extend the code. The code base, which in any software company should be a valuable asset, can become overloaded at some point. These negative processes can cause premature aging of software, which is well explained in Martin Fowler's work "Refactoring. Improving Existing Code."

Action areas




A strategically important factor is the attention of executives and software developers. On the practical side, application of development methods will slow this aging. Refactoring can reverse this aging if used correctly, preferably with good software tools that help in detecting, analyzing and describing problems, and ultimately allow them to be fixed.

Rewriting a component is often used by the developer as a more acceptable method, since it is less confusing for it. At least that is how Fowler thinks when refactoring improving existing code. The current source code may change over time from the original design and may not be immediately understood by the developer.

However, he ignores the fact that the source code has a lot of hidden meaning. Bug fixes contained in the source code may not be documented, but they are very valuable. Refactoring preserves this hidden value, ensuring that system behavior does not change.

Method rename process

This example applies to a variable, class, or other java element that has a misleading name and needs to know how to refactor such code. This requires all links and possibly file updates. A process may include renaming a method in subclasses. On the other hand, renaming a package will also include moving files and directories and updating the version control system.

Method rename process




Correction Methods:

  1. Moving class. The class is in the wrong package, so it should be moved to another package, where it works best.
  2. Extraction. The long method needs to be broken down into steps to increase readability and ease of maintenance. A section of code with one logical task is replaced by a call to a new method.
  3. Superclass Extraction. An existing class provides functionality that needs to be changed in some way. An abstract class is introduced as the parent of the current class, and then the general behavior is “pulled” to this new parent.
  4. Replacing a conditional value with polymorphism. Methods in the class can check some value (if or a switch statement) to determine the correct action to perform.

Method Advantages

Performing several refactoring operations before or during code debugging has certain advantages. It often becomes easier to locate the error. Thus, the time spent working on the code is saved and its quality is improved. Well-structured code is also less error prone when it comes to extending it. Experts say that using the method adds the benefits of any program that has at least one of the following disadvantages:

  1. Programs that are hard to read and hard to change.
  2. Programs with double logic.
  3. Programs that require additional behavior that require code changes.
  4. Programs with complex conditional logic that are difficult to modify.
Method advantages




To summarize, it can be argued that real benefits usually come in the long run, for example, when refactoring improvements to existing pdf code. They consist in significantly reduced time that developers spend on debugging and maintenance work to improve code reliability. In addition, code duplication is reduced, and code reuse is encouraged. The total cost of maintenance and development should decrease, and the speed of the response team to changing needs should increase.

Disadvantages of software fix

Disadvantages of software fix




If there are so many undeniable advantages from well-structured, understandable code, and if refactoring software code leads from chaotic, poorly structured, error-prone code to well-thought-out code, then the logical question arises, why not all software developers do it? In practice, software developers are often reluctant to make improvements because some refactoring is simply tedious. Especially when there is no apparent external benefit to this.

Project management may also be to blame. When the manual only supports the externally visible properties of the code, such as functionality and performance, but does not pay attention to the internal quality of the code.

In addition, there is a serious risk of code breaking through refactoring operations. And if, for example, file names change, traceability can also be a problem.

Even if a software developer wants to reorganize some kind of poorly structured code. His manager may have a completely different perspective on software execution and may oppose any attempt to change working code.

These problems cannot simply be ignored; they must be taken into account, as appropriate, by both developers and management.

Process automation

When refactoring, the external observable behavior must be guaranteed to remain unchanged. If it is done manually, you must often rebuild the system and run tests. Therefore, the manual method is really practical only if the following conditions are met:

  1. The system from which the reorganized code is part can be quickly restored.
  2. There are automatic "regression" tests that you can run often.

This situation is not very common and means that refactoring applications are limited. It is becoming more common, especially when more and more people are using XP (Extreme Programming) development methods.

Another obstacle to the method is that many of these refactoring are tedious. More importantly, confidence that the correct changes have been made.

Therefore, when performing software improvements, it is recommended to use automatic tools. The speed of their work has another advantage, which manifests itself in a team development environment. A developer is much less likely to perform refactoring if the involved source code also belongs to other developers.

Integration with developers who have chosen an IDE also brings many benefits. Firstly, having tools at hand means developers can more easily reorganize. They do not need to switch between development and refactoring modes and instead see this as part of their normal development cycle. Secondly, IDE functions, such as version control integration, can reduce the efforts of a method, such as moving a class or renaming a package.

Visual Studio 2017 Code Analysis

Premature optimization can be the root of all evil, but the use of tools will ensure the clarity, purity and security of the code. Testing the application before submitting it is an important part of the development process. It is here that the tools and methods of code analysis and profiling come into force - they allow you to evaluate the code for errors, bottlenecks and efficient use of processing resources and memory.

Modern code profiling tools can point directly to exact lines of code that need refactoring, or to libraries and other dependencies that are weak points in the application architecture.

Visual Studio 2017 Code Analysis




Prior to Visual Studio 2012, most of these types of code analysis and testing required third-party tools and manual assembly, testing, analysis, and repetition tasks for the developer. Today, Visual Studio has some pretty robust analysis tools. In addition, there are excellent tools to help the developer delve into the application for testing performance and optimization, project templates that have effective dependencies and built-in test environments, as well as reliable tools for integrating automated analysis and testing in assembly and release workflows.

Performance Debugging Tools

A comprehensive set of built-in tools for refactoring improving the design of existing code was first grouped into a performance and diagnostic concentrator in Visual Studio 2013, which was further improved and expanded in the “Debugging Performance and Diagnostics” and “Scanned Tools” windows in Visual Studio 2015.

With Visual Studio 2017, these tools are so integrated into the development environment that they no longer have a fancy name, but they continue to evolve. The program is equipped with excellent documentation and guidance on Microsoft documents, starting with the sections “Getting Started with Performance Tools” and “Beginner's Guide to Performance Profiling in Visual Studio”.

Performance debugging tools




The user will find information on data collection and profiling at run time of the method, not only for traditional .NET Framework applications, but also for JavaScript products, ASP.NET and websites, high performance computing (HPC) and load testing.

Another tool that developers enjoy using is code refactoring with PerfView for performance analysis. Morrison is a senior architect at Microsoft and wrote PerfView for internal performance analysis and tuning with the teams creating the .NET Framework and Visual Studio. Now it is an open source tool that is still under active development.

Additional mechanisms for profiling and debugging

In addition to the tools available from Microsoft, third-party tools are used to meet the fine-tuning needs:

  1. Jains dotTrace Profiler helps track runtime, garbage collection, workload distribution, I / O performance. There is a 10-day trial available for trial steps.
  2. Redgate ANTS Performance Profiler - another popular tool for projects based on the .NET Framework provides the same code synchronization analysis as other tools, but also delves into database query performance with support for advanced data access profiling with support for Oracle, MySQL, and PostgreSQL.
  3. DevExpress CodeRush is another parsing and refactoring tool for C #, Visual Basic, and XAML databases. CodeRush analysis tools not only work with core solutions, but also have integrated test integration that supports the NUnit, xUnit, MSpec and MSTest frameworks, as well as CoreCLR test cases in the DNX environment.
  4. Microsoft Code Analysis 2017 gives built-in access to over 100 of the most popular FxCop rules as live analyzers. Analyzers look at C # or Visual Basic code as you type and provide tips on performance, security and best practices, as well as access to a quick fix code dictionary.
  5. Microsoft DevSkim is a more comprehensive and flexible structure of modules and code analyzers focused on built-in code security analysis as you type. Potential security problems are highlighted in the code by links to additional information with a single click to a safe alternative code.

Dates

Using automatic refactoring tools makes it more likely that the developer will complete the necessary steps in a timely manner, which reduces the likelihood of errors. But no less important is the choice of dates for its holding.

Planned refactoring improves code performance by eliminating duplication. The key here is to fix it as soon as possible before it becomes a problem. In this case, continuous refactoring is used, which is very important for continuous code delivery.

Dates




In the best case, developers often switch between all the refactoring types mentioned above. At the same time, the type name does not matter, but its execution time is important.

For example, if, while reading the code, the developer understands that classes or methods can be done better, you need to do it right away without delay, using ordinary methods to extract large crashes or rename methods for better readability. This Martin Fowler Workflows platform helps users better know, plan, and implement improvement.

That is why every programmer needs to know not only what code refactoring is, but also when to execute it correctly.




All Articles