Misplaced Pages

Code refactoring

Article snapshot taken from Wikipedia with creative commons attribution-sharealike license. Give it a read and then ask your questions in the chat. We can research this topic together.

This is an old revision of this page, as edited by 103.68.176.128 (talk) at 07:39, 28 December 2021. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Revision as of 07:39, 28 December 2021 by 103.68.176.128 (talk)(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff) Restructuring existing computer code without changing its external behavior "Refactor" redirects here. For the use of "refactor" on Misplaced Pages, see Misplaced Pages:Refactoring talk pages. This article is about a behaviour-preserving change. Not to be confused with Rewrite (programming).

In computer programming and thesoftware design, code refactoring is the process of restructuring existing computer code—changing the factoring—without changing its external behavior. Refactoring is intended to improve the design, structure, and/or implementation of the software (its non-functional attributes), while preserving its functionality. Potential advantages of refactoring may include improved code readability and reduced complexity; these can improve the source code's maintainability and create a simpler, cleaner, or more expressive internal architecture or object model to improve extensibility. Another potential goal for refactoring is improved performance; software engineers face an ongoing challenge to write programs that perform faster or use less memory.

Typically, refactoring applies a series of standardised basic micro-refactorings, each of which is (usually) a tiny change in a computer program's source code that either preserves the behaviour of the software, or at least does not modify its conformance to functional requirements. Many development environments provide automated support for performing the mechanical aspects of these basic refactorings. If done well, code refactoring may help software developers discover and fix hidden or dormant bugs or vulnerabilities in the system by simplifying the underlying logic and eliminating unnecessary levels of complexity. If done poorly, it may fail the requirement that external functionality not be changed, and may thus introduce new bugs.

By continuously improving the design of code, we make it easier and easier to work with. This is in sharp contrast to what typically happens: little refactoring and a great deal of attention paid to expediently adding new features. If you get into the hygienic habit of refactoring continuously, you'll find that it is easier to extend and maintain code.

— Joshua Kerievsky, Refactoring to Patterns

Motivation

Refactoring is usually motivated by noticing a code smell. For example, the method at hand may be very long, or it may be a near duplicate of another nearby method. Once recognized, such problems can be addressed by refactoring the source code, or transforming it into a new form that behaves the same as before but that no longer "smells".

For a long routine, one or more smaller subroutines can be extracted; or for duplicate routines, the duplication can be removed and replaced with one shared function. Failure to perform refactoring can result in accumulating technical debt; on the other hand, refactoring is one of the primary means of repaying technical debt.

Benefits

There are two general categories of benefits to the activity of refactoring.

  1. Maintainability. It is easier to fix bugs because the source code is easy to read and the intent of its author is easy to grasp. This might be achieved by reducing large monolithic routines into a set of individually concise, well-named, single-purpose methods. It might be achieved by moving a method to a more appropriate class, or by removing misleading comments.
  2. Extensibility. It is easier to extend the capabilities of the application if it uses recognizable design patterns, and it provides some flexibility where none before may have existed.

Performance engineering can remove inefficiencies in programs, known as software bloat, arising from traditional software-development strategies that aim to minimize an application's development time rather than the time it takes to run. Performance engineering can also tailor software to the hardware on which it runs, for example, to take advantage of parallel processors and vector units.

Challenges

Refactoring requires extracting software system structure, data models, and intra-application dependencies to get back knowledge of an existing software system. The turnover of teams implies missing or inaccurate knowledge of the current state of a system and about design decisions made by departing developers. Further code refactoring activities may require additional effort to regain this knowledge. Refactoring activities generate architectural modifications that deteriorate the structural architecture of a software system. Such deterioration affects architectural properties such as maintainability and comprehensibility which can lead to a complete re-development of software systems.

Code refactoring activities are secured with the software intelligence when using tools and technics providing data about algorithms and sequences of code execution. Providing a comprehensible format for the inner-state of software system structure, data models, and intra-components dependencies is a critical element to form a high-level understanding and then refined views of what needs to be modified, and how.

Testing

Automatic unit tests should be set up before refactoring to ensure routines still behave as expected. Unit tests can bring stability to even large refactors when performed with a single atomic commit. A common strategy to allow safe and atomic refactors spanning multiple projects is to store all projects in a single repository, known as monorepo.

With unit testing in place, refactoring is then an iterative cycle of making a small program transformation, testing it to ensure correctness, and making another small transformation. If at any point a test fails, the last small change is undone and repeated in a different way. Through many small steps the program moves from where it was to where you want it to be. For this very iterative process to be practical, the tests must run very quickly, or the programmer would have to spend a large fraction of their time waiting for the tests to finish. Proponents of extreme programming and other agile software development describe this activity as an integral part of the software development cycle.

Techniques

Here are some examples of micro-refactorings; some of these may only apply to certain languages or language types. A longer list can be found in Martin Fowler's refactoring book and website. Many development environments provide automated support for these micro-refactorings. For instance, a programmer could click on the name of a variable and then select the "Encapsulate field" refactoring from a context menu. The IDE would then prompt for additional details, typically with sensible defaults and a preview of the code changes. After confirmation by the programmer it would carry out the required changes throughout the code.

  • Techniques that allow for more understanding
    • Program Dependence Graph - explicit representation of data and control dependencies
    • System Dependence Graph - representation of procedure calls between PDG
    • Software intelligence - reverse engineers the initial state to understand existing intra-application dependencies
  • Techniques that allow for more abstraction
    • Encapsulate field – force code to access the field with getter and setter methods
    • Generalize type – create more general types to allow for more code sharing
    • Replace type-checking code with state/strategy
    • Replace conditional with polymorphism
  • Techniques for breaking code apart into more logical pieces
    • Componentization breaks code down into reusable semantic units that present clear, well-defined, simple-to-use interfaces.
    • Extract class moves part of the code from an existing class into a new class.
    • Extract method, to turn part of a larger method into a new method. By breaking down code in smaller pieces, it is more easily understandable. This is also applicable to functions.
  • Techniques for improving names and location of code
    • Move method or move field – move to a more appropriate class or source file
    • Rename method or rename field – changing the name into a new one that better reveals its purpose
    • Pull up – in object-oriented programming (OOP), move to a superclass
    • Push down – in OOP, move to a subclass
  • Automatic clone detection

Hardware refactoring

While the term refactoring originally referred exclusively to refactoring of software code, in recent years code written in hardware description languages (HDLs) has also been refactored. The term hardware refactoring is used as a shorthand term for refactoring of code in hardware description languages. Since HDLs are not considered to be programming languages by most hardware engineers, hardware refactoring is to be considered a separate field from traditional code refactoring.

Automated refactoring of analog hardware descriptions (in VHDL-AMS) has been proposed by Zeng and Huss. In their approach, refactoring preserves the simulated behavior of a hardware design. The non-functional measurement that improves is that refactored code can be processed by standard synthesis tools, while the original code cannot. Refactoring of digital HDLs, albeit manual refactoring, has also been investigated by Synopsys fellow Mike Keating. His target is to make complex systems easier to understand, which increases the designers' productivity.

History

The first known use of the term "refactoring" in the published literature was in a September, 1990 article by William Opdyke and Ralph Johnson. Griswold's Ph.D. thesis, Opdyke's Ph.D. thesis, published in 1992, also used this term. Although refactoring code has been done informally for decades, William Griswold's 1991 Ph.D. dissertation is one of the first major academic works on refactoring functional and procedural programs, followed by William Opdyke's 1992 dissertation on the refactoring of object-oriented programs, although all the theory and machinery have long been available as program transformation systems. All of these resources provide a catalog of common methods for refactoring; a refactoring method has a description of how to apply the method and indicators for when you should (or should not) apply the method.

Martin Fowler's book Refactoring: Improving the Design of Existing Code is the canonical reference.

The terms "factoring" and "factoring out" have been used in this way in the Forth community since at least the early 1980s. Chapter Six of Leo Brodie's book Thinking Forth (1984) is dedicated to the subject.

In extreme programming, the Extract Method refactoring technique has essentially the same meaning as factoring in Forth; to break down a "word" (or function) into smaller, more easily maintained functions.

Refactorings can also be reconstructed posthoc to produce concise descriptions of complex software changes recorded in software repositories like CVS or SVN.

Automated code refactoring

This section needs additional citations for verification. Please help improve this article by adding citations to reliable sources in this section. Unsourced material may be challenged and removed.
Find sources: "Code refactoring" – news · newspapers · books · scholar · JSTOR (July 2018) (Learn how and when to remove this message)

Many software editors and IDEs have automated refactoring support. It is possible to refactor application code as well as test code. Here is a list of a few of these editors, or so-called refactoring browsers.

See also

References

  1. ^ Kerievsky, Joshua (2004). Refactoring to Patterns. Addison Wesley.
  2. ^ Fowler, Martin (1999). Refactoring. Improving the Design of Existing Code. Addison-Wesley. pp. 63ff. ISBN 978-0-201-48567-7.
  3. Suryanarayana, Girish (November 2014). Refactoring for Software Design Smells. Morgan Kaufmann. p. 258. ISBN 978-0128013977.
  4. Martin, Robert (2009). Clean Code. Prentice Hall.
  5. Leiserson, Charles E.; Thompson, Neil C.; Emer, Joel S.; Kuszmaul, Bradley C.; Lampson, Butler W.; Sanchez, Daniel; Schardl, Tao B. (2020). "There's plenty of room at the Top: What will drive computer performance after Moore's law?". Science. 368 (6495): eaam9744. doi:10.1126/science.aam9744. PMID 32499413.
  6. Haendler, Thorsten; Neumann, Gustaf (2019). "A Framework for the Assessment and Training of Software Refactoring Competences". Proc. Of 11th International Conference on Knowledge Management and Information Systems (KMIS).: 307–316. doi:10.5220/0008350803070316. ISBN 978-989-758-382-7. S2CID 204754665.
  7. Nassif, Matthieu; Robillard, Martin P. (November 2017). "Revisiting turnover-induced knowledge loss in software projects". 2017 IEEE International Conference on Software Maintenance and Evolution (ICSME): 261–272. doi:10.1109/ICSME.2017.64. ISBN 978-1-5386-0992-7. S2CID 13147063.
  8. van Gurp, Jilles; Bosch, Jan (March 2002). "Design erosion: problems and causes". Journal of Systems and Software. 61 (2): 105–119. doi:10.1016/S0164-1212(01)00152-2.
  9. Hassan, Ahmed E.; Xie, Tao (November 2010). "Software intelligence: the future of mining software engineering data". In Proceedings of the FSE/SDP Workshop on Future of Software Engineering Research (FoSER '10): 161–166. doi:10.1145/1882362.1882397. S2CID 3485526.
  10. Novais, Renato; Santos, José Amancio; Mendonça, Manoel (2017). "Experimentally assessing the combination of multiple visualization strategies for software evolution analysis". Journal of Systems and Software. 128: 56–71. doi:10.1016/j.jss.2017.03.006.
  11. 1963-, Fowler, Martin (1999). Refactoring : improving the design of existing code. Reading, MA: Addison-Wesley. ISBN 978-0201485677. OCLC 41017370. {{cite book}}: |last= has numeric name (help)CS1 maint: multiple names: authors list (link)
  12. Smart, John Ferguson (2008). Java Power Tools. "O'Reilly Media, Inc.". p. 301. ISBN 9781491954546. Retrieved 26 July 2018.
  13. ^ (these are only about OOP however).Refactoring techniques in Fowler's refactoring Website
  14. Ferrante, Jeanne; Ottenstein, Karl J.; Warren, Joe D. (July 1987). "The program dependence graph and its use in optimization". ACM Transactions on Programming Languages and Systems. 9 (3). ACM: 319–349. doi:10.1145/24039.24041. S2CID 505075.
  15. Donglin, Linag; Harrold, M. J. (November 2008). "Slicing objects using system dependence graphs". Proceedings. International Conference on Software Maintenance. IEEE: 319–349. doi:10.1109/ICSM.1998.738527. ISBN 978-0-8186-8779-2. S2CID 18160599.
  16. Replace type-checking code with State/Strategy
  17. Replace conditional with polymorphism
  18. Bruntink, Magiel, et al. "An evaluation of clone detection techniques for crosscutting concerns." Software Maintenance, 2004. Proceedings. 20th IEEE International Conference on. IEEE, 2004.
  19. Hardware description languages#HDL and programming languages
  20. Kaiping Zeng, Sorin A. Huss, "Architecture refinements by code refactoring of behavioral VHDL-AMS models". ISCAS 2006
  21. M. Keating :"Complexity, Abstraction, and the Challenges of Designing Complex Systems", in DAC'08 tutorial Archived 2016-03-28 at the Wayback Machine"Bridging a Verification Gap: C++ to RTL for Practical Design"
  22. M. Keating, P. Bricaud: Reuse Methodology Manual for System-on-a-Chip Designs, Kluwer Academic Publishers, 1999.
  23. Opdyke, William F.; Johnson, Ralph E. (September 1990). "Refactoring: An Aid in Designing Application Frameworks and Evolving Object-Oriented Systems". Proceedings of the Symposium on Object Oriented Programming Emphasizing Practical Applications (SOOPPA). ACM.
  24. ^ Griswold, William G (July 1991). Program Restructuring as an Aid to Software Maintenance (PDF) (Ph.D. thesis). University of Washington. Retrieved 2011-12-24.
  25. ^ Opdyke, William F (June 1992). Refactoring Object-Oriented Frameworks (Ph.D. thesis). University of Illinois at Urbana-Champaign. Archived from the original (compressed Postscript) on 2019-12-16. Retrieved 2008-02-12.
  26. ^ Martin Fowler, "MF Bliki: EtymologyOfRefactoring"
  27. Brodie, Leo (2004). Thinking Forth. pp. 171–196. ISBN 0-9764587-0-5. Archived from the original on 16 December 2005. Retrieved 3 May 2020.
  28. Sokolov, Andriy. "What is code refactoring?".
  29. Xuan, Jifeng; Cornu, Benoit; Martinez, Matias; Baudry, Benoit; Seinturier, Lionel; Monperrus, Martin (2016). "B-Refactoring: Automatic test code refactoring to improve dynamic analysis". Information and Software Technology. 76: 65–80. doi:10.1016/j.infsof.2016.04.016.
  30. What's new in Xcode 9
  31. Refactoring in Qt Creator

Further reading

External links

Categories: