HOME

TheInfoList



OR:

In computer programming and
software design Software design is the process by which an agent creates a specification of a software artifact intended to accomplish goals, using a set of primitive components and subject to constraints. Software design may refer to either "all the activity ...
, 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 Complexity characterises the behaviour of a system or model whose components interact in multiple ways and follow local rules, leading to nonlinearity, randomness, collective dynamics, hierarchy, and emergence. The term is generally used to ch ...
; these can improve the source codes maintainability and create a simpler, cleaner, or more expressive internal
architecture Architecture is the art and technique of designing and building, as distinguished from the skills associated with construction. It is both the process and the product of sketching, conceiving, planning, designing, and constructing buildings ...
or object model to improve
extensibility Extensibility is a software engineering and systems design principle that provides for future growth. Extensibility is a measure of the ability to extend a system and the level of effort required to implement the extension. Extensions can be th ...
. 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 standardized basic ''micro-refactorings'', each of which is (usually) a tiny change in a computer program's source code that either preserves the behavior 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 Vulnerability refers to "the quality or state of being exposed to the possibility of being attacked or harmed, either physically or emotionally." A window of vulnerability (WOV) is a time frame within which defensive measures are diminished, com ...
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.


Motivation

Refactoring is usually motivated by noticing a
code smell In computer programming, a code smell is any characteristic in the source code of a program that possibly indicates a deeper problem. Determining what is and is not a code smell is subjective, and varies by language, developer, and development me ...
. 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. # 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. #
Extensibility Extensibility is a software engineering and systems design principle that provides for future growth. Extensibility is a measure of the ability to extend a system and the level of effort required to implement the extension. Extensions can be th ...
. 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
software intelligence Software Intelligence is insight into the structural condition of software assets produced by software designed to analyze database structure, software framework and source code to better understand and control complex software systems in Informatio ...
when using tools and techniques 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 In computer programming, unit testing is a software testing method by which individual units of source code—sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures&md ...
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 In the field of computer science, an atomic commit is an operation that applies a set of distinct changes as a single operation. If the changes are applied, then the atomic commit is said to have succeeded. If there is a failure before the atomic ...
. A common strategy to allow safe and atomic refactors spanning multiple projects is to store all projects in a single
repository Repository may refer to: Archives and online databases * Content repository, a database with an associated set of data management tools, allowing application-independent access to the content * Disciplinary repository (or subject repository), an ...
, 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 In software development, agile (sometimes written Agile) practices include requirements discovery and solutions improvement through the collaborative effort of self-organizing and cross-functional teams with their customer(s)/ end user(s), ad ...
describe this activity as an integral part of the
software development cycle In software engineering, a software development process is a process of dividing software development work into smaller, parallel, or sequential steps or sub-processes to improve design, product management. It is also known as a software devel ...
.


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.(these are only about OOP however
Refactoring techniques in Fowler's refactoring Website
/ref> 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 A context menu (also called contextual, shortcut, and pop up or pop-up menu) is a menu in a graphical user interface (GUI) that appears upon user interaction, such as a right-click mouse operation. A context menu offers a limited set of choice ...
. 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 Software Intelligence is insight into the structural condition of software assets produced by software designed to analyze database structure, software framework and source code to better understand and control complex software systems in Informatio ...
- reverse engineers the initial state to understand existing intra-application dependencies * Techniques that allow for more
abstraction Abstraction in its main sense is a conceptual process wherein general rules and concepts are derived from the usage and classification of specific examples, literal ("real" or "concrete") signifiers, first principles, or other methods. "An abst ...
** 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 Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
into a new method. By breaking down code in smaller pieces, it is more easily understandable. This is also applicable to
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
s. * Techniques for improving names and location of code ** Move method or move field – move to a more appropriate
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differently ...
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 In computer programming, duplicate code is a sequence of source code that occurs more than once, either within a program or across different programs owned or maintained by the same entity. Duplicate code is generally considered undesirable for a ...


Hardware refactoring

While the term ''refactoring'' originally referred exclusively to refactoring of software code, in recent years code written in hardware description languages has also been refactored. The term ''hardware refactoring'' is used as a shorthand term for refactoring of code in hardware description languages. Since hardware description languages 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 hardware description languages, albeit manual refactoring, has also been investigated by
Synopsys Synopsys is an American electronic design automation (EDA) company that focuses on silicon design and verification, silicon intellectual property and software security and quality. Products include tools for logic synthesis and physical design ...
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 Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
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 Forth or FORTH may refer to: Arts and entertainment * ''forth'' magazine, an Internet magazine * ''Forth'' (album), by The Verve, 2008 * ''Forth'', a 2011 album by Proto-Kaw * Radio Forth, a group of independent local radio stations in Scotla ...
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 Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
) 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

Many software editors and
IDEs Ides or IDES may refer to: Calendar dates * Ides (calendar), a day in the Roman calendar that fell roughly in the middle of the month. In March, May, July, and October it was the 15th day of the month; in other months it was the 13th. **Ides of Mar ...
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. *
DMS Software Reengineering Toolkit The DMS Software Reengineering Toolkit is a proprietary set of program transformation tools available for automating custom source program analysis, modification, translation or generation of software systems for arbitrary mixtures of source langu ...
(Implements large-scale refactoring for C, C++, C#, COBOL, Java, PHP and other languages) * Eclipse based: ** Eclipse (for Java, and to a lesser extent, C++, PHP, Ruby and JavaScript) ** PyDev (for
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pr ...
) ** Photran (a Fortran plugin for the Eclipse IDE) * Embarcadero Delphi * IntelliJ based: ** Resharper (for C#) ** AppCode (for
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
, C and C++) ** IntelliJ IDEA (for Java) ** PyCharm (for
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pr ...
) ** WebStorm (for JavaScript) ** PhpStorm (for PHP) ** Android Studio (for Java and C++) * JDeveloper (for Java) * NetBeans (for Java) *
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan K ...
: Most dialects include powerful refactoring tools. Many use the original refactoring browser produced in the early '90s by Ralph Johnson. * Visual Studio based: ** Visual Studio (for .NET and C++) **
CodeRush CodeRush Classic is a refactoring and productivity plugin by DevExpress that extends native functionality of Microsoft Visual Studio (Visual Studio .NET 2012, 2013, 2015, 2017 and 2019). CodeRush Classic provides solution-wide static code analy ...
(addon for Visual Studio) **
Visual Assist Visual Assist is a plug-in for Microsoft Visual Studio developed by Whole Tomato Software. The plug-in primarily enhances IntelliSense and syntax highlighting. It also enhances code suggestions, provides refactoring commands, and includes spell ch ...
(addon for Visual Studio with refactoring support for C# and C++) * Wing IDE (for
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pr ...
) * Xcode (for C,
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
, and Swift) * Qt Creator (for C++, Objective-C and QML)


See also

* Amelioration pattern * Code review *
Database refactoring A database refactoring is a simple change to a database schema that improves its design while retaining both its behavioral and informational semantics. Database refactoring does not change the way data is interpreted or used and does not fix bugs ...
*
Decomposition (computer science) Decomposition in computer science, also known as factoring, is breaking a complex problem or system into parts that are easier to conceive, understand, program, and maintain. Overview There are different types of decomposition defined in comput ...
*
Modular programming Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functi ...
* Obfuscated code *
Prefactoring Prefactoring is the application of experience to the creation of new software systems. Its relationship to its namesake refactoring is that lessons learned from refactoring are part of that experience. Experience is captured in guidelines that c ...
*
Separation of concerns In computer science, separation of concerns is a design principle for separating a computer program into distinct sections. Each section addresses a separate '' concern'', a set of information that affects the code of a computer program. A concern ...
* Software peer review * Test-driven development


References


Further reading

* * * * * * *


External links


What Is Refactoring?
(c2.com article)
Martin Fowler's homepage about refactoring
* {{Authority control Extreme programming Technology neologisms