C Primer Plus (5th Edition)
When you start out writing programs, each program might seem like an entirely separate project, designed and constructed from scratch. However, this is not a prudent way to create computer programs, and it's not the way most programs are created today.
There is a much better alternative reuse of pre-constructed and pre-tested programs or parts of programs.
A high degree of reuse means far less code to write and allows you to tap into well-designed, well-tested software components written by highly skilled experts.
Note
Even the simplest C# programs, including the first few you will encounter in this book, rely on software reuse under the hood. |
The following example illustrates the value of reuse.
You want to build a simple radio. You can follow two paths to accomplish this task.
You can build every component you need from scratch (resistors, transistors, chips and so on). You will need a lot of knowledge, talent, money, and time to build each of these sophisticated components yourself. In fact, you might not finish the project for many years.
Alternatively, you could purchase the electronic components you need from the local electronics retail shop. For a relatively small cost, you utilize the expertise and big investments involved in manufacturing the components and, before you know it, you will have built a brand new radio.
Software reuse can take many shapes; the following are only two of many:
Reuse of individuals lines of code This is a simple form of reuse and involves copying lines of code from one part of a program to another. However, because the same code is replicated perhaps many places in the same program, the benefits are somewhat limited.
The "class" as a unit of reuse One of the major enticements of an object-oriented language like C# is the elaborate support for code reuse. The class in particular turns out to be a very good reuse unit.
To illustrate this fact, recall the elevator simulation example presented earlier. Due to the success of this project, another company called Very Big Finance Ltd. has requested that we perform a simulation involving a larger building and more elevators. Initially, it seems we have to dispose of the previous project entirely and start from scratch. However, closer scrutiny reveals that the new elevators are more or less unchanged. Due to its object-oriented design, the Elevator class from the previous project contains and encapsulates all the attributes and methods needed for it to function as an elevator in this new project. Consequently, it is relatively easy to slot the Elevator into our new program and reuse it here as a software component.
Reuse is at the core of .NET and C# programming, and we will frequently return to this topic throughout the book. In fact, this is an important part of the next section.