In software development (and computer programming in general), code reuse, also called software reuse, is the use of existing software, or software knowledge, to build new software,  following the reusability principles.

Code reuse may be achieved by different ways depending on a complexity of a programming language chosen and range from a lower-level approaches like code copy-pasting (e.g. via snippets), simple functions (procedures or subroutines) or a bunch of objects or functions organized into modules (e.g. libraries) or custom namespaces, and packages, frameworks or software suites in higher-levels.

Code reuse implies dependencies which can make code maintainability harder. At least one study found that code reuse reduces technical debt.

Overview

Ad hoc code reuse has been practiced from the earliest days of programming. Programmers have always reused sections of code, templates, functions, and procedures. Software reuse as a recognized area of study in software engineering, however, dates only from 1968 when Douglas McIlroy of Bell Laboratories proposed basing the software industry on reusable components.

Code reuse aims to save time and resources and reduce redundancy by taking advantage of assets that have already been created in some form within the software product development process. The key idea in reuse is that parts of a computer program written at one time can be or should be used in the construction of other programs written at a later time.

Code reuse may imply the creation of a separately maintained version of the reusable assets.  While code is the most common resource selected for reuse, other assets generated during the development cycle may offer opportunities for reuse: software components, test suites, designs, documentation, and so on.

The software library is a good example of code reuse. Programmers may decide to create internal abstractions so that certain parts of their program can be reused, or may create custom libraries for their own use. Some characteristics that make software more easily reusable are modularity, loose coupling, high cohesion, information hiding and separation of concerns.

For newly written code to use a piece of existing code, some kind of interface, or means of communication, must be defined. These commonly include a "call" or use of a subroutine, object, class, or prototype. In organizations, such practices are formalized and standardized by domain engineering, also known as software product line engineering.

The general practice of using a prior version of an extant program as a starting point for the next version, is also a form of code reuse.

Some so-called code "reuse" involves simply copying some or all of the code from an existing program into a new one. While organizations can realize time to market benefits for a new product with this approach, they can subsequently be saddled with many of the same code duplication problems caused by cut and paste programming.

Many researchers have worked to make reuse faster, easier, more systematic, and an integral part of the normal process of programming. These are some of the main goals behind the invention of object-oriented programming, which became one of the most common forms of formalized reuse. A somewhat later invention is generic programming.

Another, newer means is to use software "generators", programs which can create new programs of a certain type, based on a set of parameters that users choose. Fields of study about such systems are generative programming and metaprogramming.

Types of reuse
Concerning motivation and driving factors, reuse can be:
 Opportunistic – While getting ready to begin a project, the team realizes that there are existing components that they can reuse.
 Planned – A team strategically designs components so that they'll be reusable in future projects.

Reuse can be categorized further:

 Internal reuse – A team reuses its own components. This may be a business decision, since the team may want to control a component critical to the project.
 External reuse – A team may choose to license a third-party component. Licensing a third-party component typically costs the team 1 to 20 percent of what it would cost to develop internally. The team must also consider the time it takes to find, learn and integrate the component.

Concerning form or structure of reuse, code can be:
 Referenced – The client code contains a reference to reused code, and thus they have distinct life cycles and can have distinct versions.
 Forked – The client code contains a local or private copy of the reused code, and thus they share a single life cycle and a single version.

Fork-reuse is often discouraged because it's a form of code duplication, which requires that every bug is corrected in each copy, and enhancements made to reused code need to be manually merged in every copy or they become out-of-date. However, fork-reuse can have benefits such as isolation, flexibility to change the reused code, easier packaging, deployment and version management.

Systematic

Systematic software reuse is a strategy for increasing productivity and improving the quality of the software industry. Although it is simple in concept, successful software reuse implementation is difficult in practice. A reason put forward for this is the dependence of software reuse on the context in which it is implemented. Some problematic issues that need to be addressed related to systematic software reuse are: 
a clear and well-defined product vision is an essential foundation to a software product line (SPL).
an evolutionary implementation strategy would be a more pragmatic strategy for the company.
there exist a need for continuous management support and leadership to ensure success.
an appropriate organisational structure is needed to support SPL engineering.
the change of mindset from a project-centric company to a product-oriented company is essential.

Examples

Software libraries

A very common example of code reuse is the technique of using a software library. Many common operations, such as converting information among different well-known formats, accessing external storage, interfacing with external programs, or manipulating information (numbers, words, names, locations, dates, etc.) in common ways, are needed by many different programs. Authors of new programs can use the code in a software library to perform these tasks, instead of "re-inventing the wheel", by writing fully new code directly in a program to perform an operation. Library implementations often have the benefit of being well-tested and covering unusual or arcane cases. Disadvantages include the inability to tweak details which may affect performance or the desired output, and the time and cost of acquiring, learning, and configuring the library.

Design patterns

A design pattern is a general solution to a recurring problem. Design patterns are more conceptual than tangible and can be modified to fit the exact need. However, abstract classes and interfaces can be reused to implement certain patterns.

Frameworks

Developers generally reuse large pieces of software via third-party applications and frameworks. Though frameworks are usually domain-specific and applicable only to families of applications.

Higher-order function

In functional programming higher-order functions can be used in many cases where design patterns or frameworks were formerly used.

Retrocomputing

Retrocomputing encompasses reuse of code, simply because retro programs are being run on older computers, or emulators for them.

Computer security
In computer security code-reuse is employed as a software exploit method.
When an attacker is not able to directly input code to modify the control flow of a program, for example in presence of code injection defenses such as W^X, he or she can redirect the control flow to code sequences existing in memory.

Examples of code-reuse attacks are return-to-libc attack, return-oriented programming, and jump-oriented programming.

Components

A component, in an object-oriented extent, represents a set of collaborative classes (or only one class) and its interfaces. The interfaces are responsible for enabling the replacement of components. Reusable components can also be isolated and synchronized between SCM repositories using component source code management technologies (CSCM).

Outside computers
The whole concept of "code reuse" can also encompass engineering applications outside software. For instance, parametric modeling in computer-aided design allows for creating reusable designs. Standardization results in creation of interoperable parts that can be then reused in many contexts.

Criticism 
Code reuse results in dependency on the component being reused. Rob Pike opined that "A little copying is better than a little dependency". When he joined Google, the company was putting heavy emphasis on code reuse. He believes that Google's codebase still suffers from results of that former policy in terms of compilation speed and maintainability.

Reusable code requires usually more effort to write and design. Fred Brooks discusses the significantly higher cost associated with that effort in his essays "The Tar Pit" and "No Silver Bullet" The fallacy is that effort is often spent without careful understanding of the mechanisms through which that cost will be redeemed. The justification often comes from incorrectly drawing parallels to reusable parts in a physical manufacturing process. Incorrect because writing code is analogous to design of a single product rather than production of multiple units.

See also
Don't repeat yourself
International Conference on Software Reuse
Inheritance (object-oriented programming)
Language binding
Not invented here (antonym)
Type polymorphism
Procedural programming
Reinventing the wheel (antonym)
Reusability
Reuse metrics
Single source of truth
Software framework
Virtual inheritance

References

External links
 ReNews – an information site about software reuse and domain engineering
 Software Reuse Tips Article

Programming principles
Repurposing
Computer libraries
코드 재사용(code 再使用) 또는 소프트웨어 재사용(software 再使用)은 기존의 소프트웨어 또는 소프트웨어 지식을 활용해, 새로운 소프트웨어를 구축하는 일이다. 단순한 재사용은 프로그래밍의 여명기로부터 행해져 왔다. 프로그래머는 템플릿, 함수, 프로시저와 같이 항상 코드의 일부를 재사용하고 있다. 소프트웨어 재사용은 소프트웨어 공학의 연구 대상으로 여겨져 1968년에 벨 연구소의 더글러스 맥일로이(Douglas McIlroy)가 재사용가능한 콤포넌트에 기반한 소프트웨어 산업을 제창한 것이 시초이다.

개요 
재사용가능한 소프트웨어나 소프트웨어 지식은 재사용가능한 자산이다. 자산에는 설계, 요구명세, 검사, 아키텍처 등도 포함된다.

아마 가장 잘 알려져 있는 재사용 가능 자산은 코드이다. 코드 재사용은 어떤 시점에 쓰여진 프로그램의 일부 또는 전부를 이후의 다른 프로그램을 만들 때 사용하는 것이다. 코드의 재사용은 장황한 작업에 소비하는 시간과 에너지를 절약하는 전형적 기법이다.

라이브러리는 추상화가 좋은 예이다. 프로그래머는 프로그램의 일부를 재사용가능하게 하기 위해서 내부에 추상화 포인트를 작성하거나 자기 부담으로 사용하기 위해서 커스텀 라이브러리를 만들거나 한다. 소프트웨어를 보다 재사용하기 쉽게 하는 특성을 모듈성, 저결합도, 고응집도, 캡슐화, 관심의 분리 등으로 부른다.

기존 코드를 사용하여 새로운 코드를 만드는 경우, 하등의 인터페이스 혹은 액세스 수단이 정의되어 있지 않으면 안 된다. 이것에는 서브루틴 호출, 오브젝트, 클래스, 프로토 타입 등이 포함되는 것이 일반적이다. 기업에서는 이것들을 정식화, 표준화해두는 것이 일반적이다.

어떤 프로그램의 이전 버전을 출발점으로 하여 다음의 버전을 개발하는 작업도 일종의 코드 재사용이다.

코드 재사용의 한 형태로서 기존의 프로그램으로부터 코드를 일부 또는 전부 뽑아내 새로운 프로그램에 복사해넣는 일이 있다. 기업은 개발을 빠르기 하기 위해서 이 방법을 쓰기도 하지만, 이렇게 복사와 붙여넣기를 많이 하면, 차후에 중복 코드로 문제가 될 수 있다.

재사용을 빠르고 용이하게 하기 위해 프로그래밍 정식 절차의 일부로서 보다 체계적으로 실시할 수 있도록 하는 연구가 많이 이루어져 왔다. 객체지향 프로그래밍도 그러한 목적에서 만들어진 것으로 정식화된 재사용기법으로서 일반화되었다. 같은 목적으로 후에 개발된 것으로서 제네릭프로그래밍이 있다.

한층 더 새로운 수단으로서 자동 프로그래밍이 있다. 이것은 프로그램이 사용자가 설정한 일련의 변수에 근거하여 어떤 종류의 프로그램을 생성하는 것이다.유사한 개념으로 메타 프로그래밍도 있다.

재사용의 형태 
 편의적 재사용(opportunistic reuse)
 프로젝트를 시작할 때 재사용가능한 콤포넌트가 있는지를 찾아보고 재사용한다.
 계획적 재사용(planned reuse)
 컴퍼넌트를 차후에 재사용가능하도록 전략적으로 설계해 나간다.

편의적 재사용은 다음으로 더 세분화할 수 있다.
 내부 재사용(internal reuse)
 팀내에서 만든 콤포넌트를 재사용한다. 어디까지나 편의상이며 계획적인 것이 아니기 때문에, 인터페이스의 조정 등에 추가적인 비용이 발생할 수 있다.
 외부 재사용(external reuse)
 서드파티에서 만든 콤포넌트를 구하여 사용한다. 유상인 경우, 조달비용을 자신이 직접 개발할 때 드는 비용의 20% 이하로 잡는 것이 일반적이다. 또, 조달한 콤포넌트를 학습하여 활용하는데 걸리는 시간도 고려해야 한다.

예시 
소프트웨어 라이브러리
코드 재사용의 매우 일반적인 예로서 라이브러리를 사용하는 것이다. 각종 형식으로 정보의 변환, 외부기억장치 액세스, 외부 프로그램과의 인터페이스, 정보(수, 단어, 이름, 위치, 날짜 등)의 조작이라고 한 일반적인 조작은, 많은 프로그램으로 필요하게 된다. 새로운 프로그램을 쓸 때, 라이브러리의 코드를 사용해 그것들 작업을 실행하도록 할 수 있어 차바퀴의 재발명과 같이 같은 조작을 실행하는 프로그램을 또 만들어 쓸 필요는 없다. 라이브러리의 실장은 특수한 사례도 포함하여 자주 평가되고 있다고 하는 이점이 있다. 결점은, 성능 향상이나 출력 형식을 바꾸고자 할 때 세부사항을 조절할 수 없는 점과 라이브러리를 취득·학습·설정하는 데에 시간과 비용이 든다는 점이다.

디자인 패턴
디자인 패턴은 비슷한 문제를 풀기 위한 범용적인 해법이다. 디자인 패턴은 개념적이고, 개별 문제의 필요에 따라서 수정 가능하다. 추상 클래스와 인터페이스는 특정의 패턴의 실장에 재사용 가능하다.

 체제

서드파티 응용 프로그램이나 체제를 통해 소프트웨어의 큰 부분을 재사용하는 것도 많다. 다만 체제는 통상 특정 영역에 고유한 것으로, 광범위하게 응용하기는 어렵다.

같이 보기 
 Don't repeat yourself
 상속
 수속형 프로그래밍
 다형성
 가상 상속
 소프트웨어 콤포넌트
 차바퀴의 재발명
 NIH 증후군

소프트웨어 공학