Refactoring

In a nutshell, refactoring is the art of small and continual improvements to the design of our code while preserving its behavior. The intention is to create behavior-preserving transformations to our system which ultimately make it more maintainable. 

Each time we change parts of our software, we purposely refactor parts of the code that are in our path. To ensure we preserve current behavior, we use automated tests which tell us if our code is still working as we refactor.

Using Ron's analogy of fields, thickets, and bushes from the previous section, instead of mowing around the bushes, with refactoring, we cut a path through each bush we encounter. It looks a little like the following:

 

We do need coding standards when refactoring; a good starting point is Clean Code: A Handbook of Agile Software Craftsmanship, by Robert "Uncle Bob" C. Martin. Coding standards are hygiene factors which should be possible to automate using tools such as SonarQube—an open source tool for automating code reviews and the static analysis of code.

One of the principal causes of bugs in our software is complexity, primarily because it makes our code hard to read. If the code is hard to comprehend, it causes developers to make mistakes because they misinterpret how it functions. Over time, it will even affect the developer who wrote it, and they may struggle to maintain their original intentions.

We should always be thinking about how we can make things more easily readable. Sound naming conventions, fewer lines per method, fewer paths, and loose coupling of code are just a few examples.

Remember, it's relative. Some areas may need more attention than others. Definite red flags requiring attention are units of code with many lines; aim to decompose these into more manageable chunks.

Also look for places that have a high cyclomatic complexity. These are hotspots for attention because the code in these locations has multiple paths running through it, often obscuring some or all of its purpose.

You can refactor without automated tests, but you have to do it carefully. You will need to manually test a lot and use tools that you trust, for example, there are automated refactoring tools for Java and C#.

For instance, most modern IDEs have simple refactoring support, so when changing a method signature, the IDE will help locate and modify it throughout the codebase.

Some tools are purpose built and more sophisticated than those provided by an IDE. Re-sharper by JetBrains is one example which plugs into Visual Studio.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.106.135