Real-World Considerations
local graph
Chapter 18 — Real-World Considerations
Section titled “Chapter 18 — Real-World Considerations”REAL-WORLD CONSIDERATIONS
Section titled “REAL-WORLD CONSIDERATIONS”Since this book is intended as a companion for someone learning to code, you hopefully know something about software at this point and about the hardware on which it runs as well. You might think that you’re ready to be a programmer. But programming involves more than knowing about hardware and writing code. How do you know what code to write, and how do you go about writing it? How do you know that it works?
Those aren’t the only important questions you face. Can others figure out how to use your code? How easy is it for others to add features or find and fix bugs? How hard is it to make your code run on hardware other than that for which it was originally written?

[!visual-conversion] cartoon robot in hard hat holding a sign with ‘LY … Cropped from the scan (PDF page 453, printed p. 413): cartoon robot in hard hat holding a sign with ‘LY GE’ visible
This chapter covers various topics related to the creation of software. While you can do small projects yourself sitting in a dark room with a sufficient quantity of junk food, most projects are a team sport that involves dealing with people. That’s harder than you might think—the hardware/software systems that we call people are way buggier than even the most terrifying internet-of-things abomination. And forget about documentation; even if you could find any, it would be out-of-date.
That’s why this chapter also covers some of the philosophical and practical issues around being a programmer. Yup, this is where the old curmudgeon tries to pass on some hard-earned wisdom.
The Value Proposition
Section titled “The Value Proposition”There’s an overarching question that you should keep in mind when working on a project: “Am I adding value?” I’m not talking about the intrinsic value of accomplishing some task here; I’m talking about increasing productivity.
If you’re programming for a living, you need to meet whatever goals your employer has set. But, of course, there’s more than one way to meet those goals. You could just do what you need to do to get by. Or, you could put a little thought into things that might not have occurred to management. For example, you might realize that your code would be useful in another project and structure it so it’s easily reusable. Or, you might sense that you were tasked to implement a special case of a more general problem and solve that general problem instead, paving the way for future enhancements. Of course, you should talk about this with management so that they’re not surprised.
You can add value to yourself by making sure that you’re proficient in a variety of technologies. Side projects are a common way to get experience; it’s equivalent to doing homework but more fun.
One classic way in which people attempt to add value is by creating tools. This is trickier than it seems because sometimes adding value for yourself reduces value for others. People often create new tools because some feature that they think they need is missing from existing ones. A good example is the make utility (invented by Stuart Feldman at Bell Labs in 1976), which is used to build large software packages. As time went on, new features were needed. Some of these were added to make, but in many other cases, people created well-intentioned but incompatible new utilities that performed similar functions. (For example, I consulted for a company once that wrote their own solely because they didn’t bother to completely read the make documentation and were unaware that it would do exactly what they needed.) Now there’s make, cmake, dmake, imake, pick-a-letter-make, and other programs that all do similar things in incompatible ways. The result is that practitioners like you need to learn multiple tools in each category. It makes everyone’s life harder, not easier. It doesn’t add value—it detracts. Figure 15-1 sums up the situation nicely.
HOW STANDARDS PROLIFERATE:
Section titled “HOW STANDARDS PROLIFERATE:”(SEE: A/C CHARGERS, CHARACTER ENCODINGS, INSTANT MESSAGING, ETC.)
|
SITUATION: THERE ARE 14 COMPETING STANDARDS. |
14?! RIDICULOUS! WE NEED TO DEVELOP ONE UNIVERSAL STANDARD THAT COVERS EVERYONE’S USE CASES. YEAH!

|
SOON: SITUATION: THERE ARE 15 COMPETING STANDARDS. |
Figure 15-1: Not adding value (courtesy of Randall Munroe, xkcd.com)
Creating burdens for others doesn’t add value. Experienced programmers know that doing something that’s already been done in a way that they personally prefer rarely adds value. Instead, it shows off one’s immaturity as a programmer. Improve existing tools wherever possible because more people will be able to use the result. Save making new tools for new things. Make sure that you fully understand existing tools because they might be more capable than you realized at first glance.
Mucking up the ecosystem into which you release code does not add value. Many developers behave as if they’re stereotypical Americans vacationing in another country, or for that matter my father-in-law visiting—the “I just came to your place, so do things my way” attitude.
For example, UNIX systems have a command that displays manual pages for programs. You can type man foo and it’ll show you the page for the foo command. There’s also a convention that really complex commands, such as yacc, have both a manual page and a longer, more in-depth document that describes the program in more detail. When the GNU project (which I’ll discuss shortly) added commands to UNIX, it used its own texinfo system for manuals, which wasn’t compatible with the man system. The result was that users would have to try both the man and info commands to find documentation. Even if, as some believe, the GNU approach was superior, any possible benefits were outweighed by the UNIX community’s huge loss of productivity that resulted from the fragmented ecosystem.
There are many other examples, such as the replacement of the init system with systemd. A big part of the UNIX philosophy, as discussed later in this chapter, is modular design, but systemd replaced the modular init system with a huge monolithic beast. There was no attempt to retrofit new features into the existing system. The entire user base lost productivity because they had to learn a new system that mostly did just what the old one did. It would have added more value to add multithreading and other new features to the existing system.
Yet another example is the jar utility, which is part of the Java programming environment. The tar utility was created in the 1970s to pack multiple files into a single one. This solved a problem caused by using magnetic tape for storage. Mag tape is a block device, and packing files together allowed full blocks to be used thereby increasing efficiency. ZIP files, which first made their appearance on Windows, are similar. Rather than using either of these existing formats, though, Java made its own. The result was that users now needed to learn yet another command for no particularly good reason.
So don’t be the programmer equivalent of an “ugly American.” Work with the ecosystem, not against it. Use the rule of “least astonishment” as a guide. You’ve added value if your work seems a natural extension of the existing environment.
How We Got Here
Section titled “How We Got Here”Before we get going on more practical issues, let’s look at how we got here. Much more has happened in the field than we can cover here, so we’ll just touch on some important historical highlights and a few more recent developments.
A Short History
Section titled “A Short History”A long time ago, people made money selling computers, which were really expensive. Software was written and given away in order to help sell computers. There was a culture of sharing and working together to improve software. More and more people wrote and shared software as computers became more accessible.
The Multics operating system, which ran on the huge GE645 mainframe computer, was collaboratively developed in the 1960s by Bell Telephone Laboratories, General Electric, and the Massachusetts Institute of Technology. Bell pulled out of the project, and some of the people there who had worked on it—most notably, Ken Thompson and Dennis Ritchie—went off to experiment with some filesystem ideas they’d had when working on Multics using the smaller computers produced by the Digital Equipment Corporation (DEC). Their work resulted in an innovative new operating system called UNIX, which embodied a new minimalist and modular philosophy for software. While not planned at the outset, it became the first portable operating system, meaning it could run on more than one type of computer. The term UNIX in this book refers to all similar systems including Linux, FreeBSD, NetBSD, OpenBSD, and the modern macOS. Microsoft Windows is the only major outlier, but even it is incorporating more and more UNIX features—for example, the socket model for networking.
Bell wasn’t the only Multics participant to go their own way. The Incompatible Timesharing System (ITS) was developed over at MIT. While ITS included a number of groundbreaking features, its most influential contribution is arguably the Emacs (Editor MACroS) text
editor, which began as a set of macros for the DEC TECO (Text Editor and Corrector) text editor. The user interface for ITS and Emacs influenced the GNU project, also started at MIT.
Ken Thompson brought a copy of UNIX with him in 1975 when he took a sabbatical year to teach at the University of California, Berkeley. This had a huge effect that still reverberates today. Students had access to a real working system. They could examine the code to see how things worked, and they could make changes. Not only that, but they were exposed to the philosophy as well. Berkeley produced its own version of UNIX, called BSD for Berkeley Software Distribution.
Students added many new important features to the system. BBN’s networking stack, which is the foundation of the internet, was integrated into UNIX at Berkeley, where the now-ubiquitous socket interface was born. University graduates started to use the BSD version of UNIX and formed companies such as Sun Microsystems, which made commercial UNIX-based systems.
Personal computers changed this. All of a sudden the people writing software weren’t the people selling computers, so they needed to charge for it. But there was still an attitude of “it’s great that we make a living doing this cool stuff.” This changed dramatically when Bill Gates (one of the founders of Microsoft) came on the scene. As is evident from numerous court depositions, his focus was on making money. If he had to do something cool to make money, he would, but his priorities were opposite those of others in the industry. How did this change things?
Software development began to be driven more by politics, lawyers, and sometimes-underhanded behavior than by superior engineering. This approach frequently focused on suppressing innovation that competed with existing products. For example, Microsoft started with MS-DOS, a program that they bought from its developer, American computer programmer Tim Paterson. Microsoft let the program languish, as they were making plenty of money from it. A company called Digital Research came out with an improved version called DR-DOS. When Microsoft released Windows, the original version of which ran on top of DOS, they included a hidden, encrypted piece of code that checked to see whether the system was running MS-DOS or DR-DOS and generated phony errors if it found DR-DOS. This made DR-DOS unsuccessful in the marketplace even though it was arguably a better product for the money.
It wasn’t just Microsoft, however. Apple also sued Digital Research for “copying” their user interface in a product called GEM. Digital Research would probably have prevailed eventually, but would have gone bankrupt in the process because Apple had much deeper pockets. It’s somewhat ironic when you realize that the Apple user interface was substantially copied from the Xerox Alto.
Unfortunately, this mindset continues today with threatened big players resorting to the courts instead of innovating their way out of their difficulties. Examples abound, such as SCO versus IBM, Oracle versus Google, Apple versus Samsung, Samsung versus Apple, Intellectual Ventures shell companies versus the world, and so on.
Personal computers started becoming popular in the mid-1980s. It wasn’t practical to run UNIX on them because the hardware lacked a memory management unit (see Chapter 5), although there was a variant called Xenix that did run on the original IBM PC hardware.
Colleges started using personal computers running Microsoft Windows to teach computer science because they were cheaper. However, unlike the UNIX-era graduates from UC Berkeley and other schools, these students weren’t able to look at the source code of the system they were using. And the system with which they became familiar was considerably less advanced than UNIX. As a result, graduates from this era are often not of the same quality as their earlier counterparts.
In part as a reaction to the closed nature of the source code, Richard Stallman started the GNU (Gnu’s Not Unix) project in 1983. Among other things, the goal was to create a freely available and legally unencumbered version of UNIX. Today we call this “free and open source software,” or FOSS. Open source means that the source code is available for others to see, and more importantly, modify and improve. Stallman, working with his lawyer, created the copyleft, a variant of the copyright used by others to protect their software. The copyleft essentially said that others were free to use and modify the code as long as they made their modifications available under the same terms. In other words, “we’ll share our code with you if you share yours with everyone else.” The GNU project did a great job of re-creating the UNIX utilities such as cp and, possibly most important, the gcc C compiler. But the project team was slow to create an operating system itself.
Linus Torvalds began work on what is now known as the Linux operating system in 1991, partly because there was no GNU operating system. To a large degree, this work was made possible by both the existence of the GNU tools such as the C compiler and the nascent internet, which enabled collaboration. Linux has become extremely popular. It’s used heavily in data centers (the cloud), it’s the underlying software in Android devices, and it’s used in many appliances. This book was written on a Linux system.
Large companies were originally skeptical about using open source software. Who would fix the bugs? This is somewhat ludicrous; if you’ve ever reported a bug to Microsoft, Apple, or any other large company, you know how much attention it gets. In 1989, John Gilmore, DV Henkel-Wallace (a.k.a. Gumby), and Michael Tiemann founded Cygnus Support to provide commercial support for open source software. Its existence greatly increased the willingness of companies to use open source software.
In many ways, Linux and GNU have brought us a new golden era similar to the Berkeley UNIX days. It’s not quite as shiny, though, because some of the people from the PC era are making changes without really understanding the philosophy. In particular, some programmers who didn’t grow up with UNIX are reducing the value of the ecosystem by replacing small modular components with huge monolithic programs.
Open Source Software
Section titled “Open Source Software”Open source software is widely successful despite alarmist propaganda by some established closed source companies. For example, senior Microsoft personnel claimed, “Open source is an intellectual property destroyer. I can’t imagine something that could be worse than this for the software business and the intellectual property business,” despite the fact that they were secretly using open source tools in-house. A main advantage of open source software is that many more eyeballs are available to look at the code, which translates into benefits such as greater security and reliability. Another is that it allows programmers to build on work that others have done instead of having to reinvent everything. Even if you use a closed source computer system, there’s a pretty good chance that you’re still using some open source components. Even Microsoft recently appears to have seen the light and makes many UNIX tools available on their systems.
The development of open source software was greatly enhanced by the internet and cloud services. It’s trivial to find open source projects or to start your own. But—and this is a big but—the majority of open source projects out there are garbage just like their closed source counterparts.
A lot of open source software comes from student projects. Since they’re often first projects, the authors haven’t yet mastered the art of writing good code. And much of this software is unfinished, as the student programmers completed their class, graduated, or just moved on. It’s often easier to rewrite something than it is to decipher someone else’s poorly written and documented code. This is a vicious cycle because the rewrite often doesn’t get done, so there are multiple versions that don’t work in different ways. For example, I recently needed to extract tags from MP3 files and tried six different open source programs, each of which failed in a different way. It’s often difficult to determine whether or not there is a good working version of something because there is so much litter.
When Richard Stallman started the GNU project, he assumed that the world was filled with programmers of similar quality to him and his peers. That assumption didn’t turn out to be valid. There is still a belief that one of the advantages of open source software is that you can add features and fix bugs that you find. Unfortunately, much of this software is poorly written and completely undocumented, making the amount of effort too great for a casual user or even an experienced programmer.
Just because something is open source doesn’t mean that it’s a great example of the craft. But you can learn what not to do just as well as you can learn what to do from looking at other people’s code.
Here are two indicators, one positive and one negative, that you can use to help determine the quality of a piece of code.
The positive indicator is whether or not a project is under active development with more than one contributor. This doesn’t apply to projects that have been around for a long time and are actually “done.” It often helps if a project is supported by some organization. Many of the major open source
projects originated at companies that still support their development. However, you must be wary of open source projects created at companies that are later acquired by other companies with different philosophies. For example, Sun Microsystems was a prodigious developer of open source software, including OpenOffice, Java, and VirtualBox. However, Sun was acquired by Oracle, which ended support for some of these projects and tried to find ways to control and monetize others; see the Oracle versus Google lawsuit for details. Other projects have been donated by companies to foundations that support their development. This often yields a consistent vision that keeps the project on track. This indicator is not completely reliable, so take it with a grain of salt. For example, the code base for the Firefox web browser is a poorly documented mess.
The negative indicator is the type and quantity of dialog that you’ll see at various programmer “self-help” websites. If you see lots of “I can’t figure out how to make this work” and “Where do I start to make this change?” questions, then it’s probably not a great piece of code. Furthermore, if the responses are mostly useless nonanswers or are snarky and unhelpful, then the project probably lacks good developers. Developers who blame the questioner for their own lack of quality work are not good role models. Of course, it’s also a bad sign if there are no comments or questions at all, as it means that the code is probably not used.
Cautionary tales aside, open source is a great thing. Make your code open source when it makes sense to do so. But first, learn how to do a good job so that your code becomes a good example to others.
Creative Commons
Section titled “Creative Commons”The copyleft worked well for software, but software isn’t the only area in which society benefits from the ability to build on the past. When the copyleft was first created, most computer applications were text based; graphics, images, audio, and video were too expensive for the average consumer. Today, the sounds and visuals that are part of programs are arguably as important as the programs themselves.
American lawyer and academic Lawrence Lessig recognized the importance of artistic works and created a set of licenses for them similar to the copyleft called Creative Commons. There are many variants of these licenses, just like there are a variety of open source licenses for software. These range from “you can do anything you want” to “you have to give the creator credit” to “you have to share all of your changes” to “noncommercial use only” to “no derivative works allowed.”
The Creative Commons legal framework has greatly enhanced our ability to build on the work of others.
The Rise of Portability
Section titled “The Rise of Portability”The term portability has a specific meaning for software. Code that is portable can run in a different environment than the one for which it was developed. That may be a different software environment, different hardware, or
both. Portability wasn’t an issue in the early days of computing when there were just a handful of computer vendors, although standard languages like COBOL and FORTRAN allowed programs to be run on different machines. It became more important in the 1980s when the EDA industry (see “Hardware vs. Software” on page 90) and the availability of UNIX enabled the formation of a much larger number of computer companies.
These new computer vendors ported UNIX to their products; their customers didn’t have to worry about it. But another change happened at about the same time, which is that these less-expensive UNIX systems made inroads into the commercial market instead of being limited to academia. Source code was not shipped with many of these systems since the end users would never be building programs themselves. And, in an effort to increase profits, some companies started charging extra for certain UNIX tools, such as the C compiler. People who needed these tools started turning to the GNU tools since they were free, and often at least as good—and in many cases better than—the original UNIX tools.
But now, users had to port these tools to different systems themselves, which quickly became a huge pain point. Different systems had header files and libraries in different places, and many of the library functions had subtle differences in their behavior. This was addressed in two different ways. First, standards such as POSIX (portable operating system interface) were created to bring some consistency to the APIs and user environments. Second, the GNU project created a set of build tools, such as automake, autoconf, and libtool, to automate some of the system dependency checking. Unfortunately, these tools are incredibly cryptic and hard to use. Plus, they have their own dependencies, so code built with a particular version often can’t be built with another.
This is the state of the world today. Modern systems are more similar than they used to be because the world is pretty much UNIX based. And, while they’re clunky, the GNU build tools get the job done most of the time.
Package Management
Section titled “Package Management”Open source software, especially Linux, exacerbated the problem of distributing software. While people refer to Linux as if it’s a single system, there are many different configurations—from what’s used in data centers to desktops to the base for Android phones and tablets. Even if all systems had the same configuration, there are many different versions of each system. While source code is available, a lot of code is now distributed in precompiled, ready-to-run form.
We talked about shared libraries back in “Running Programs” on page 137. A precompiled program won’t work unless the system includes the right versions of the libraries on which it depends. Some large programs use huge numbers of libraries, and all of them need to be present and of the versions that the programs expect.
While there were some earlier attempts, package management really took off with Linux. Package management tools allow programs to be bundled into packages that include a list of dependencies. Package management tools
such as apt, yum, and dnf not only download and install software but also check the target system for dependencies, downloading and installing them as necessary.
These tools work a good part of the time. But they tend to run into problems when different programs need different versions of the same dependencies. And, since package managers aren’t compatible, it’s a lot of work to get software ready to be installed on different systems.
Containers
Section titled “Containers”Containers are a more recent, different approach to the package management problems. The idea is that an application and all of its dependencies are bundled up into a container. The container is then run in an environment where all of its pieces, such as data files, are kept isolated from the rest of the system.
Containers simplify software deployment because they bundle up all of the dependencies (libraries and other programs) required by an application into a single package. This means that, provided your type of container is supported, you can just install a containerized application without having to worry about other things that it needs. A downside of this approach is that it effectively eliminates shared libraries (see “Running Programs” on page 137), resulting in less efficient memory utilization. Containers are also larger than applications by themselves.
Security is touted as a benefit of containers. The idea is that running multiple applications on the same operating system allows applications to interfere with each other by leveraging OS bugs. While that may be true, it just means that a different class of bugs needs to be exploited.
Containerized applications called snaps are an option on many Linux systems. CoreOS, now Container Linux, is one of the major Linux container efforts. One of the developers was among the first people to suffer through the course notes that were the foundation of this book, so you’re in good company.
The Java programming language was created by a team at Sun Microsystems led by James Gosling starting in 1991. Gosling has a track record of recognizing when technology has changed to the point where a different approach becomes practical. In this case, he realized that machines were fast enough that interpreters were a practical alternative to compiled code in many circumstances. The Java language looks a lot like C and C++.
One of the ideas behind Java was that rather than recompiling your code for every target machine, someone would do that for the Java interpreter and then your code would just run. You would only have to write your code once and run it anywhere. This wasn’t a completely original concept, as Java wasn’t the first interpreted language.
Java was originally designed for television set-top boxes (back when it was called Oak). It was repurposed as a way to run code in browsers that was independent of the machine on which the browser was running. It has been
somewhat eclipsed by JavaScript in that environment, although it’s still used. JavaScript is unrelated to Java, and is not quite as nice a language, but it’s much easier to write since it doesn’t require any special tools.
Java is important because it has become a popular teaching language. This is partly due to the fact that it uses garbage collection, which frees beginners from the complexity of explicit memory management. It’s a great place to start as long as you don’t stop there.
Java has become much more than a language; there is a whole ecosystem of software that surrounds it. That ecosystem includes a lot of custom tools and file formats, making life more difficult for programmers. The ecosystem is so complicated and fragmented that it’s not uncommon to hear programmers grumble that while they only have to write code once, getting the ecosystem installed and functional so that they can actually run that code is often pretty difficult.
Another downside to Java is the programming culture that has grown up around it. Java programmers tend to use hundreds of lines of code where one would suffice. When looking at someone else’s Java code, you often wonder where to find the line that actually does something. Some of this stems from Java being a good object-oriented language. Fanatics obsess over having a beautiful class hierarchy and often prioritize that over getting a job done.
A good example is a Java database tool called Hibernate, which, as far as I can tell, tries to solve two “problems.” The first is that Java classes and subclasses do a great job of data hiding, or limiting the visibility of internal variables. But, despite the data hiding, code at the bottom of the class hierarchy accesses a global database, which causes some people to freak out philosophically. Hibernate uses special comments in Java to provide database manipulation, hiding reality from the programmer. Of course, this is all well and good until something breaks, at which time reality must be faced.
The second thing that Hibernate does is to provide an abstraction called HQL (Hibernate Query Language) on top of the underlying database API, which is usually SQL (Structured Query Language). In theory, this allows programmers to perform database operations without having to worry about the differences between database systems.
Back before the C programming language was formally standardized, there were a number of incompatibilities between compilers. Rather than invent a “meta-C,” people came up with programming guidelines like “don’t use this feature.” By following these guidelines, code would work on any compiler.
The differences between SQL implementations can be handled in a similar way without introducing yet another mechanism. It’s also worth noting that most serious SQL projects include something called stored procedures for which there is no compatibility among implementations. And HQL doesn’t provide support for them, so it missed out on the one place where it could have been really useful.
The feel-good value of hiding the underlying database system is not balanced out by having to learn a new language that doesn’t do everything you need.
Node.js
Section titled “Node.js”As you’ve seen in this book, JavaScript began life as a scripting language for browsers. Node.js is the latest environment that allows JavaScript to be run outside of a browser. One of its primary attractions is that it allows both the client and server sides of an application to be written in the same programming language.
While the idea is good, the results vary. I avoid Node.js for a couple of reasons. First, Node.js invented its own package manager. Just what everyone needed—another incompatible method making it harder to maintain systems. As a contrast, even though Perl has its own package manager, it avoids decreasing value by making its packages available via system package managers such as apt and dnf.
Second, there are hundreds of thousands of Node.js packages with twisty interdependencies. The vast majority are not suitable for serious work. For some reason, Node.js attracts bad code.
Cloud Computing
Section titled “Cloud Computing”Cloud computing means using someone else’s computers over a network. It’s not really a new concept; it’s an updated version of the 1960s invention of time sharing. Two factors make cloud computing interesting:
-
Networks have become more ubiquitous and speeds have increased dramatically. This makes functionality like streaming audio and video possible, not to mention offloading storage for things like email.
-
Hardware prices have come down to the point where an incredible amount of computing power and storage is available. This has led to new algorithms and ways to solve problems that were previously not practical. Of course, the same can be said for desktop computers. My current machine has eight processor cores, 64GB of RAM, and 28TiB of disk. This was neither practical nor economical when I started programming. Another way of looking at it is that the machine on which I’m writing this book has more RAM than the total amount of disk storage on the machine that I used 20 years ago.
There’s nothing really magical about cloud computing; it’s just hardware and software. It has created new business models for renting computing resources.
Cloud computing has sparked a lot of innovation in hardware packaging. Data centers have completely different economies of scale, and reliability is important. Cramming huge numbers of machines into a space means paying a lot of attention to power and cooling. One creative scheme pioneered by Sun Microsystems involves building data centers in shipping containers instead of buildings.
Virtual Machines
Section titled “Virtual Machines”It used to be that one program would run on one computer at a time. Operating systems made it possible to run multiple programs via time sharing. But not all application programs that users wanted were available on all operating systems, especially when closed source systems became the norm. Many users had to resort to using multiple computers running different operating systems, or having to reboot their machine to run different operating systems.
Hardware is now fast enough that entire operating systems can be considered applications, making time sharing between multiple operating systems practical. Keep in mind that this might require interpreting an instruction set that is different than that of the underlying physical machine. Also, it’s not enough just to be able to run the instruction set—the expected hardware environment must be present as well.
Since these operating systems aren’t necessarily running directly on the physical machine hardware, they’re called virtual machines. Virtual machines provide many advantages other than eliminating the proprietary operating system lockout. They’re really useful for development, especially for operating system development. That’s because when the system under development crashes, it doesn’t also crash your development system.
Virtual machines are a mainstay of the cloud-computing world. You can rent space in the cloud and run whatever mix of operating systems you desire.
The operating system that supports the virtual machines is often called a hypervisor.
Portable Devices
Section titled “Portable Devices”Just as with cloud computing, improvements in communication technology and hardware price/performance have made it possible to build portable devices with great power and functionality. A single modern cell phone has more computing power and storage than all of the computers in the world combined a few decades ago. Other than the portability, there’s nothing new or magical about these devices. Each has its own ecosystem and tools.
The big challenge with portable device programming is power management. Because portable devices are battery powered, great care must be taken to minimize operations such as memory accesses, as they consume power and run down the battery.
The Programming Environment
Section titled “The Programming Environment”Programming for a living is not the same thing as working on personal or school projects. Working as a programmer means taking direction from, giving direction to, and working with others. Little if anything is taught about this aspect of the field in school. It’s often learned through a series of weird on-the-job experiences.
Are You Experienced?
Section titled “Are You Experienced?”So here you are, a new programmer with little or no experience. What is experience and how do you acquire it?
Employers are always looking for “experienced professionals.” What does that mean? The simplest definition is that a candidate has exactly the sought-after skills. But that’s not really a very good definition, and it’s often impractical. For example, I received a call in 1995 from a recruiter looking for someone with five years of Java programming experience. I had to explain that even the authors of Java didn’t have that level of experience because it hadn’t been around that long.
One of the satisfying things about programming is that you get to do things that have never been done before. So how can you start with the skills that you won’t have until you’re done? What’s a good definition of experience?
First of all, you need to be grounded in the fundamentals. If all you know is how to build a website, you’re unlikely to be able to successfully contribute to a surgical robot project. But more importantly, experience is knowing what you can do and what you can’t do. How do you know what you can do when you haven’t done it yet? You need to learn to estimate. It’s not just guesswork; it’s heuristics.
Learning to Estimate
Section titled “Learning to Estimate”One of the most damaging things you can do as a member of a project team is to fail to deliver your work on time without warning. The key here is without warning; nobody delivers everything on time, but when being late is a surprise, it’s difficult for other team members to work around.
How do you learn to estimate? With practice. Start with this: before you do a task, such as a homework assignment, jot down your estimate of how long it will take. Then keep track of how long the task actually took. After a while, you might discover that you’re getting better at estimating. This is good practice because with homework, just like with programming, you’re always doing something that you haven’t done before.
An oft-abused but worthwhile management technique is status reporting: you regularly generate a short list of what you accomplished since the last report, what problems arose, and what your plans are for the next reporting period. This is just a more formal method of tracking your homework predictions. When a status report shows that the plans were not achieved but no problems were encountered, that’s a red flag. Status reporting gives you a way to adjust your estimates by comparing them to actual results.
Scheduling Projects
Section titled “Scheduling Projects”Programming projects are generally more complex than your homework (with the possible exception of your programming class homework). How do you estimate a more complex project?
A fairly simple method is to make a list of all of the pieces in the project. Put them into three appropriately sized bins, such as 1 hour, 1 day, and 1 week. Add up the results. You will probably be wrong about most of your guesses, but on average the total estimate will be pretty close. Status reporting is key here, because it shows that some things take more time than expected while others take less time, making it possible to track the original estimate.
Approaches like this are an important trade-off, because generating a complete and accurate schedule for a complex project often takes longer than just doing the project. And it still wouldn’t account for things like snow days.
Related to this is how projects actually get planned in the industry, which I explained when answering a question from the audience at an ACM lecture in 2004 at Oregon State University. It’s not really possible to convey the slack-jawed silence that followed. Goes to show, you don’t learn everything you need to know in class. What happens is that you’ll distinguish yourself by doing a great job on some project. Your manager will take you aside and say, “Hey, nice job. We’re thinking about doing this new thing. Can you tell me how long it will take and how much it’ll cost?” You’ll feel so honored that you’ll give up your social life for a while to figure it all out in detail. You’ll do this without knowing (except you will, because you’ve read this) that before your manager talked to you, they already had some numbers in mind, possibly given to them by their manager. You’ll show your results to your manager, who will respond with, “Oh. Well, you know, if it’s going to take this long and cost this much, we just won’t do it.” A light will go on in your head and you’ll ask yourself, “Do I want to have a job next week?” You’ll say, “Well, this was conservative, I can pull it in here and there.” Now, a very interesting thing is taking place. You’re lying to your manager, who knows that you’re lying. Your manager also knows that your original numbers are correct, and that the project would come in on time and on budget if you were allowed to use them. Furthermore, they know that forcing you to use the more aggressive numbers will make the project late and over budget. But sadly, that’s the way it’s often done.
While this scenario may be hard to believe, keep in mind the popularity of Dilbert comics.
As this example indicates, a common challenge in scheduling is management that refuses to accept schedules and true costs. Nonengineers often view schedules as something that can be negotiated; managers often feel that engineers are too conservative in scheduling and try to negotiate down the estimated time. This almost always leads to bigger problems down the road. The only legitimate way in which to decrease the time is to remove features.
Decision Making
Section titled “Decision Making”There are many possible ways to do most projects. There are choices of programming languages, data structures, and more. Engineers are famous for having heated debates over the “right” way to do something. Sometimes
projects don’t happen and people lose their jobs because they can never stop arguing and get down to work. Heated discussions often make management uncomfortable.
An otherwise unexceptional manager taught me something very useful about resolving these sorts of problems. At the beginning of a project, he took all of us into a conference room and told us how he worked. He said that decisions were going to be made first and foremost on technical grounds. But, he said, many times there is no technical reason for doing things one way or another. He said that in those cases, it was perfectly okay to say, “I want to do it this way because I like it.” He explained that as long as nobody else preferred a different way, then he’d go along. He didn’t want to hear complicated pseudotechnical arguments that in reality were just someone justifying their particular preference but not saying so. In that case, not only would that person not get their way, but they’d probably also lose their job. The moral of this story is to keep technical necessities separate from personal preferences.
You’ve already gotten a taste of this sort of behavior in Chapter 12, where you learned that the actual rationale for and benefits of JavaScript promises are obfuscated by a fear of pyramid-of-doom rationalization.
Working with Different Personalities
Section titled “Working with Different Personalities”I mentioned earlier in this chapter that programming usually involves working with other people.
Numerous “learn to code” boosters emphasize that “programming is fun.” I don’t agree; my sympathies are more in line with those expressed by Italian researcher Walter Vannini in his article “Coding Is Not ‘Fun’, It’s Technically and Ethically Complex.” Recall the two-step programming process from the book’s introduction. The second step, explain it to a three-year-old (that is, doing the actual programming), requires meticulous attention to detail. You’re probably at a stage where you have trouble keeping your room clean; that doesn’t translate to programming. I would say that programming is satisfying. The fun comes in the first step, understanding the problem. But even that’s not a barrel of laughs.
People in any profession have a wide range of personalities, not all of which would be described as “well adjusted.” Programmers are no exception. While many programmers have balanced personalities, some favor technical prowess over social skills. There is a wide spectrum between Richard Stallman and Dennis Ritchie, with Linus Torvalds somewhere in between. This can be a source of problems, especially in this age where people are highly sensitive to word choices.
There’s a lot of discussion in the media these days about abusive behavior in the workplace. Let me be clear: workplace abuse is never acceptable, so don’t be an abuser and don’t allow yourself to be abused. But it can often be difficult to determine what is abuse and what isn’t. That’s because people don’t have the same worldviews, and something that might be fine for one person might not be for another. The classic example is Apple founder Steve Jobs.
You might think that this issue could be addressed with some simple rules. And it can, but there are trade-offs. Many years ago, I worked with a manager who expressed it pretty well. He said that while he could force the people in his group into “good behavior,” such as being less argumentative, the result would be losing much of the creative manic energy for which he hired those people. He felt that a large part of his job was to smooth over personality differences so that people would be productive.
A big source of problems is that programmers who are passionate about their work may be intensely critical of someone else’s. A hard lesson to learn is that it’s not personal. I once had an employee who—as I eventually learned—if I pointed out a bug in his code, he would interpret that as me telling him he was a bad person. As a contrast, when that same employee took delight at pointing out bugs in my code, my reaction was, “Let’s fix it because we want this to succeed.” At the core, this is about people having confidence in themselves. Try to build the confidence of your team members, as confident people are less likely to take things personally.
Related to this, I once worked for someone who regularly told me that what I was doing was stupid. Eventually, I figured out what was happening and said the following: “You know, I finally realized that when you tell me that what I’m doing is stupid, you’re really saying that you don’t understand what I’m doing. Now that I know that, I’ll ignore you as best I can. But I’m human, so every time you say ‘stupid,’ I get less work done for the next few days. So if you want to get your money’s worth, you might try to just tell me that you don’t understand things.”
Communication is important. A characteristic of insecure people is that they try to make others feel inferior either by talking way above their level or by being condescending. The job of a secure person is to figure out how to speak to others at their level of understanding. As an example, I was at a party at the 1989 SIGGRAPH (Special Interest Group on Computer Graphics) conference and overheard someone there ask another person for help in understanding a paper written by Loren Carpenter, the first geek to win an Academy Award. This other person patiently explained the paper. Afterward, the first person said, “Hey, thanks. That really helped. My name is Joe, what’s yours?” to which the other person replied, “I’m Loren.” Be like Loren.
One more thing to keep in mind if you do end up in a difficult situation at work: Human Resources is not your friend. Their job is not to protect you; it’s to protect the company from liability.
Navigating Workplace Culture
Section titled “Navigating Workplace Culture”Each workplace has its own unique culture. Finding one that matches your personality is key to having a successful and enjoyable career. Results-based and personality-based cultures are opposite ends of the spectrum.
Amy Wrzesniewski, Clark McCauley, Paul Rozin, and Barry Schwartz’s 1997 article “Jobs, Careers, and Callings: People’s Relations to Their Work” partitions people’s work into the three categories in the article’s title. In short, people get financial rewards from jobs, advancement from careers, and enjoyment from callings. Matching your category and personality to your workplace is a key component of success.
Jobs and careers work better in personality-based cultures. These cultures reward drama-free personal interactions. People treat each other well, at least face-to-face.
Callings and results-based cultures go together. Getting the best job done is the reward even if doing so involves heated arguments and intense discussions.
As an example, this book’s technical editor and I spent a month having an intense argument about a paragraph in Chapter 7. We were both happy that we reached a great solution, and that happiness made up for all of the arguing. We were both annoyed that it took so long to find a solution, but that’s the way it is; sometimes solutions are not obvious. If that sort of process and outcome makes you happy, you want to find a workplace that values such behavior.
It’s worth taking a step back to reframe the problem when a solution is elusive. However, it’s difficult to remember to do this in the middle of a passionate discussion.
Making Informed Choices
Section titled “Making Informed Choices”You may have noticed that I haven’t exactly had glowing things to say about certain parts of the technology spectrum, such as the web. This may have you wondering why you’d want to work in this field. A lot depends on what you want to get out of your work, as per the previous section. Keep in mind that all endeavors have their good and bad aspects. Choose your work situations with your eyes open.
There’s often a trade-off between interesting work and making lots of money. People with callings prefer interesting work and would do it for free if necessary. People with jobs or careers often get paid handsomely for working with cumbersome or broken technology. A good example is the large number of people who remembered how to program in COBOL, who found and fixed Y2K bugs. These were bugs in antiquated code that involved dates and kept only the last two digits of the year. The transition from 1999 to 2000 would have broken this code, which was in use for lots of critical infrastructure.
Development Methodologies
Section titled “Development Methodologies”It seems like every field of endeavor spawns “methodology experts.” Programming is no different, except possibly that there is such zeal that ideology is a more appropriate term than methodology. And every methodology seems to come with its own uniform, hairstyle, terminology, and secret handshakes. To a large degree, this just makes it easier for adherents to exclude the non-believers, the opposite of the Loren Carpenter example earlier. And it can become ridiculous: I was discussing methodology with a client who finally blurted out, “As long as we have a completely Agile pivoting scrum, things should be okay.”
My expert advice is to not take any ideology too seriously. None of them work in pure form; you need to cherry-pick the ideas and use those that make sense for your project. How do you decide what works for your project? Let’s look at the various stages of development (Figure 15-2).

[!visual-conversion] Project development cycle diagram with nodes: What are we doing?, … Cropped from the scan (PDF page 471, printed p. 431): Project development cycle diagram with nodes: What are we doing?, How are we doing it?, How do we know it works?, and feedback loops to Users #1, Users #2, and Testing.
Figure 15-2: Project development cycle
We have the three questions with which we began this chapter. A big distinction between ideologies is the role of the user.
Contrary to what you might believe from observing the world around you, software is written for things other than entertainment. An ideology that works for a website or video game is probably not appropriate for a satellite, power plant, pacemaker, or car.
It’s important to know exactly what you’re doing for projects in which the cost of failure is high, so the users (#1) are involved early on in order to come up with a clear definition. Once you have a definition, you can begin coding, which is usually—and should be—reviewed by peers. The result is tested against the definition.
When the cost of failure is low, there’s less incentive to come up with a clear definition in advance. It’s common to take more of a “We’ll know it when we see it” attitude. Users (#2) play a more important role in looking at results and deciding whether or not the right thing has been done. Testing to determine whether or not the code actually works is often confused with testing to determine whether or not users like the current definition.
Laziness and incompetence are not good development methodologies. Many people don’t write specifications because they don’t know how. Choose a methodology that’s right for the project first and the people second.
Project Design
Section titled “Project Design”A project starts with an idea. It might be your idea, or it might come from someone else. How does that turn into code?
You can, of course, just start coding. And that’s just fine for small personal projects. But for anything significant, there are some processes that you can follow that lead to better results.
Writing It Down
Section titled “Writing It Down”Start by writing the idea down. You’ll be surprised by how that gets you to fill in a lot of missing details.
It’s important for your documentation to be at the correct level. Talk about what you’re going to do, not how you’re going to do it.
As an example of how not to go about it, I was once asked to help out on a project to design a new blood pressure monitor. The client sent me about 5,000 pages of documentation and asked me to estimate the cost, which I was unable to do. It turns out that, due to prior problems, company management had issued an edict that no code would be written without documentation. Sounds good, but they ignored the fact that none of their people knew how to write documentation, and they didn’t provide any training. So the engineers wrote code without telling management and then described their code in longhand English. Nowhere did their documents even mention that the product was a blood pressure monitor.
Another example is the Apache web server. Good piece of software. Tons of documentation on how to set this or that configuration parameter. Never says that it’s a web server or describes how the pieces relate.
Fast Prototyping
Section titled “Fast Prototyping”One development methodology that deserves a mention is fast prototyping. This involves whipping out a partially working version of your project. Just like writing things down, prototyping helps you to understand your idea in more depth. A prototype can also be a useful tool to help explain your idea to others.
Watch out for these pitfalls:
- Don’t mistake your prototype for production code. Throw it out and write new code using what you learned from doing the prototype.
- Don’t allow yourself to be forced into coming up with a hard schedule for the prototype. After all, a big reason for prototyping is that you don’t know enough to be able to generate a realistic schedule.
- Most difficult, don’t let your management mistake your prototype for a shippable product.
One of the hallmarks of prototype code that got shipped is a lack of coherency. In his book The Stuff of Thought (Penguin), Steven Pinker discusses the difference between working with blocks and working with the principles that govern the behavior of those blocks. You’re mainly working
with blocks during prototyping. It’s important to take a step back after the prototype is functional to observe those governing principles and then reimplement the code to use those principles consistently.
Interface Design
Section titled “Interface Design”Your project will occupy some place in a software stack; you saw an overview of this in Figure 1 on page xxxiii. Software is the filling in a sandwich that communicates with things above and below it. The interfaces that your application uses make up the bottom piece of bread. You need to define the top piece.
System programming occupies the space between the hardware and the applications. System programs communicate with hardware using whatever combination of registers and bits are detailed in the device manufacturer’s datasheets. But system programs also have to communicate with applications. The line between them is called the application program interface (API). An API is called a user interface (UI) if it’s used by people instead of by other programs. There are numerous APIs since programs are built in layers; there may be an operating system at the bottom with an API that is used by libraries, which in turn are used by applications. How is an API designed? What makes a good one?
A good way to start is to document the use cases, situations in which the API is used to accomplish some task or set of tasks. You can collect use cases by querying the eventual users of a program. But keep in mind that users often give shortsighted answers because they’re already using something. A lot of their feedback tends to be of the “make it like this with that change” variety. And a pile of discrete requirements doesn’t make for a clean result.
Now, you could just do what the users request, and it might work out for a while. But for an API to have legs, you need to abstract the user requirements and synthesize an elegant solution. Let’s look at a few examples.
The original Apple Macintosh API was published in 1985 in a three-volume set of books called Inside Macintosh (Addison-Wesley). The set was over 1,200 pages long. It’s completely obsolete; modern (UNIX-based) Macs don’t use any of it. Why didn’t this API design last?
The Mac API could be described as very wide and shallow. It had a huge number of functions, each of which did one particular thing. An argument could be made that this interface didn’t last because it was too specific; the lack of abstractions, or generalizations, made it impossible to extend as new use cases arose. Of course, more functions could have been added, making it even wider, but that’s not a very practical approach.
By contrast, version 6 of the UNIX operating system was released 10 years earlier in 1975, with a 321-page manual. It embodied a completely different approach that sported a narrow and deep API. The narrowness and depth were made possible by a good set of abstractions. What’s an abstraction? It’s a broad category of things; for example, rather than talking individually about cats, dogs, horses, cows, and so on, you could use the abstraction “animals.” These abstractions were evident not just in the system calls (see “System and User Space” on page 133) but also in the applications.
For example, you’re probably familiar with the concept of a file as a place to store data. Many operating systems had different system calls for each type of file. UNIX had a single type of file with a handful of system calls. For example, the creat system call could create any type of file. (When asked if he would do anything different if he were redesigning the UNIX system, Ken Thompson replied, “I’d spell creat with an e.”) As part of the file abstraction, even I/O devices were treated as files, as you saw in Chapter 10.
Compare this abstraction to the pip (Peripheral Interchange Program) utility on contemporary DEC systems. It was a hugely complicated and ungainly tool that had special commands that allowed users to copy files. There were specific commands to copy files to tapes, printers, and more. By contrast, UNIX had a single cp (copy) command that users could use to copy files independent of their type and where they lived. You could copy a file to an I/O port connected to a printer as easily as you could copy a file from one place to another.
The UNIX abstractions supported a novel programming philosophy:
- Each program should do one thing and do it well. Make another program to do something new instead of adding complication to old ones.
- Build programs to work together; the output of programs should be usable as input to other programs. Do complicated things by hooking simple programs together instead of writing huge monolithic programs.
Both the UNIX API and a large number of the original applications are still in widespread use today, more than 40 years later, which is a testament to the quality of the design. Not only that, but a large number of the libraries are still in use and essentially unchanged, though their functionality has been copied into many other systems. And the book The UNIX Programming Environment (Prentice Hall) by Brian Kernighan and Rob Pike is still worth a read even though it’s decades old.
A more subtle advantage of this modular approach is that new programs not only have intrinsic value but also add to the value of the ecosystem as a whole.
Switching gears slightly, I mentioned earlier that a UI is an API for users instead of other programs. In his 2004 book The Art of Unix Usability, Eric Raymond supplies an interesting case study of the Common Unix Printing System (CUPS), which gives numerous insights on how not to design user interfaces.
Designing a great interface is hard. Here are a few points to keep in mind:
- An API should not expose implementation internals. It should not depend on a particular implementation.
- APIs should exhibit conceptual heaviness, which is another way of saying that there should be good abstractions.
- APIs should be extensible, or adaptable to future needs. Good abstractions help here.
- APIs should be minimal, meaning that they shouldn’t be larded with multiple ways to do the same thing.
- Modularity is good; if an API provides related sets of functionality, make them as independent as possible. This also makes it easier to break a project into pieces so that multiple people can work on it simultaneously.
- Functionality should be composable; that is, it should be easy to combine the pieces in useful ways. (Don’t misread this as compostable. The world already has too many poorly designed interfaces rotting away.) For example, if you had an interface that returned sorted search results, it might make sense to separate out the searching and sorting so that they could be used both independently and in combination.
Unless you’ve been asleep, you’ve noticed that I’m a fan of the UNIX philosophy. This is because it works, not because it’s flashy and trendy. And it illuminates the previous points.
As we discussed earlier, one UNIX feature that is now also available on many other systems is the file abstraction. Most operations on files are not performed using the filename; instead, the filename is converted into a handle called a file descriptor, which is used instead. This abstraction allows users to perform file operations on things that are not technically files, such as connecting to something over a network.
As we saw in Chapter 10, when a program is started on UNIX, it is passed a pair of file handles called standard input and standard output. You can think of a program as a water filter in a pipe; unfiltered water flows into standard input, and filtered water pours from standard output. One of the clever things about UNIX is that the standard output of one program can be hooked to the standard input of another via something called a pipe. For example, if you had a water filter program and a water heater program, you could hook them together to get heated, filtered water without having to write a special program to do that. You can think of UNIX as a crate full of random tools and parts from which things can be built.
An amusing illustration of this philosophy occurred in 1986, when Don Knuth (professor emeritus of computer science at Stanford University and author of The Art of Computer Programming series, which you should own a copy of) wrote an article for Communications of the ACM that included more than 10 pages of code to cleverly solve a particular problem. This was followed by a critique from Doug McIlroy (Ken Thompson and Dennis Ritchie’s boss at Bell Laboratories) showing how the entire solution could be written as a single line of six pipelined UNIX commands. The moral of the story is that good general-purpose tools that can be interconnected beat one-off special solutions.
One of the things that made pipelining work was that programs mostly worked on text and thus had a common format. Programs didn’t rely on much structure in the data other than a line of text or fields separated
by some character. Some claim that this approach only worked because in “simpler times,” text could be a common format. But again, the API has legs. Program suites such as ImageMagick provide complex image-processing pipelines. Programs also exist to handle data with a more complex structure, such as XML and JSON.
Reusing Code or Writing Your Own
Section titled “Reusing Code or Writing Your Own”While defining the top-slice-of-bread interface is critical to a project, you’ll also face difficult decisions in selecting the bottom slice of bread. On what code that you didn’t write are you going to rely?
Your program will likely use libraries (see “Running Programs” on page 137) other people have written that include functions you can use instead of writing your own. How do you know when to use a library function and when to write something yourself?
At one level, this is the same problem as finding good open source software, as we discussed earlier in “Open Source Software” on page 419. If a library doesn’t have a stable API, then it’s likely that future releases will break your code. Multiply this by the number of libraries, and it’s clear that all of your time will go into fixing things instead of writing your own code. Too many libraries can make your code fragile. For example, a package on which many other packages depended was broken in Node.js recently, affecting a large number of programs.
Sometimes you need to use libraries because they implement something that takes really specialized knowledge that you don’t have. A good example of this is the OpenSSL cryptography libraries.
Some argue that using libraries is better than writing your own code because libraries in wide use have been debugged. Unfortunately, that’s not always true; the OpenSSL library is a notable example.
Normally I would say that you shouldn’t use a library when the number of lines of code to include the library exceeds the number of lines of code needed to write it yourself—for example, using glibc to implement singly linked lists. However, you also need to think about the environment in which the library is used; glibc is used by so many programs that it likely resides in memory as a shared library, so it effectively gets you code without using any memory space.
It’s often very difficult to find useful libraries. A recent article mentioned that there are over 350,000 Node.js packages. It’s probably faster to write your own code than it is to find the right needle in such a gargantuan haystack.
Project Development
Section titled “Project Development”At this point, you can hopefully create a specification for a project and a schedule for implementation. How do you turn this into reality?
Consider using Linux or some other UNIX derivative for your programming. There are many ways to do this. If you have a Mac, you’re all set because there’s a variant of UNIX underneath. You can install Linux on your PC. If that’s not practical, you can run a live image, which means running from a DVD and not changing anything on your PC’s hard drive. A better option is to run Linux in a virtual machine, which is a piece of software that lets you run a different operating system within a window on your computer. For example, you can install VirtualBox on a Windows machine and then run Linux there.
The Talk
Section titled “The Talk”Okay, it’s time for the talk. Maybe your parents were too embarrassed; maybe they thought that you’d hear about it at school. Or maybe they think that you’ll find out what you need on the internet. That’s all pretty lame. If you’re going to be a serious code slinger, you need to have an adult relationship with computers. You need to put down the mouse and learn to use a text editor.
Adult Relationships with Computers
Section titled “Adult Relationships with Computers”Your relationship with computers has been pretty childlike so far. You’ve been pointing, clicking, poking, and otherwise tickling the computer and watching it giggle in response. That doesn’t cut it for programming.
Programming involves a pretty intense relationship with a computer. You’ll be doing a lot more than just typing up a paper or watching a video—so much more that you’re going to need to be much more productive. That means that it’s time to learn how to use power tools.
Many of these tools are cryptic and a bit difficult to learn. Too bad. Once you get the hang of them, you’ll never go back because you can get so much more accomplished with much less effort. So, grit your teeth and put in the up-front work; it’ll pay off big-time later!
Terminals and Shells
Section titled “Terminals and Shells”Remember all that stuff about terminals in Chapter 6? Well, guess what? Real programmers still use ’em. Terminals don’t make a racket or do the green flash anymore. And they’re not a separate machine; they’re a piece of software that runs on the computer.
All desktop computer systems have terminals, even if they make them hard to find. By default, terminals run command interpreters. You’ll be presented with a command prompt. As you might expect, you enter commands at a command prompt. Systems rooted in UNIX—such as Apple products, Linux, and FreeBSD—have a command interpreter or shell named bash. Of course, Windows does its own thing, but it’s possible to install bash on Windows systems.
THE BASH SHELL
Section titled “THE BASH SHELL”One of the original UNIX shells, named sh, was written by Stephen Bourne. Over the years, other shells were created that had more features. Unfortunately, these new features came with personalities that were completely incompatible with sh. Eventually, a new version of sh was written that incorporated these additional features in a compatible way. This version was named bash for “Bourne-again shell.” Retaining the legacy Bourne identity was a huge value-add that resulted in supremacy among shells.
Many of the commands have cryptic names, such as grep (global regular expression printer). It’s a lot like anatomy, where many body parts are named after something else they resemble or after the person who first discovered them. For example, the awk command was named after its authors: Alfred Aho, Peter Weinberger, and Brian Kernigan. It all makes a compelling case for evolution. It’s hard to distinguish people talking about these commands from grunting cavemen.
A big reason to learn these cryptic commands is automation. A powerful shell feature is that you can put commands into a file, creating a program that runs those commands. If you find yourself doing something a lot, you can just make a command to do it for you. This is way more productive than sitting at a fancy graphical program clicking buttons and waiting for results.
Text Editors
Section titled “Text Editors”Text editors are programs that let you create and modify vanilla ASCII data, which is the stuff of which programs are made (I am completely unqualified to comment on programming languages that use non-ASCII characters such as Chinese). A main advantage of text editors is that they operate using commands, which is way more efficient than cutting and pasting stuff with a mouse—at least, once you learn them.
There are two popular text editors: vi and Emacs. Learn to use one (or both). Each has its fanatical following (Figure 15-3).

[!visual-conversion] Cartoon: child asks ‘Why are we hiding from the police, … Cropped from the scan (PDF page 478, printed p. 438): Cartoon: child asks ‘Why are we hiding from the police, daddy?’ father replies ‘Because we use vi son, they use emacs.’
Figure 15-3: vi vs. Emacs
Eclipse and Visual Studio are examples of fancy programming tools known as integrated development environments, or IDEs. (Check their release date: beware the IDEs of March.) While IDEs are great for untangling someone else’s poorly written code, you’re already lost if you need them. Going way back to the book’s introduction, learn the fundamentals before losing sight of them in fancy tools. Also, you’ll find that such tools are pretty slow and you can be much more effective with simple but powerful alternatives. For example, you can edit a program with a text editor and rebuild it faster than you can start one of these tools.
Portable Code
Section titled “Portable Code”While you may never intend to use a piece of software elsewhere, it’s surprising how often it happens. And if your code is open source, others may want to use it (or pieces of it) elsewhere. How do we write code so that it’s not overly difficult to port? The short answer is to avoid hardwiring where possible.
As you learned earlier in this book, there’s a wide variety of ways in which hardware can differ, such as the bit and byte ordering and word size. Separate from the hardware, there are differences in how programming languages present the hardware to the programmer. For example, a trouble spot in C and C++ is that the language standards don’t define whether or not a char is signed or unsigned. The workaround is to be explicit in your code.
You can use the sizeof operator in C to determine the number of bytes in a data type. Unfortunately, you need to write small programs to determine the bit and byte order. Many languages include ways to find out, for example, the largest and smallest numbers that can be stored in a particular data type.
Character sets are another troublesome area. Using UTF-8 avoids many problems.
Many programs use external libraries and other facilities. How do you insulate something like string comparison from system differences? One way is to stick to standard functionality. For example, standards such as POSIX define the behavior of library functions.
There will be differences between target environments that can’t be dealt with easily. Put as many of these dependencies as possible in a single place instead of scattering them throughout your code. That makes it easy for someone else to make the needed changes.
Just because code can be built for another system doesn’t mean that it’s a good idea. A classic example is the X Window System. In the early 1980s, Stanford graduate student Andy Bechtolsheim designed a special workstation-like personal terminal to run on the Stanford University Network. Stanford licensed the hardware design, which became the foundation of SUN Microsystems’ line of Sun Workstation products. Stanford professors David Cheriton and Keith Lantz developed the V operating system, which ran on the SUN. It featured a very fast synchronous interprocess communication mechanism, which meant that programs could communicate with each other very quickly. Paul Asente and Brian Reed developed the W window system,
which ran on the V system. This code eventually made it to MIT, where it was ported to UNIX and renamed X. But UNIX didn’t have the fast synchronous IPC; it had a slower asynchronous IPC designed for the embryonic internet. X’s performance was worse than awful, and it took a major redesign to get it up to terrible.
Source Control
Section titled “Source Control”Programs change: you add to them, you modify them to fix bugs, and so on. How do you keep track of all of your old versions? It’s important to be able to go back in time, because you may introduce a bug in a new version and need to see what changed.
Time to flog more UNIXisms. Doug McIlroy created a program called diff in the early 1970s that compared two files and generated a list of differences. This program could optionally produce output in a form that could be piped into a text editor so that users could take a file and a list of differences and produce a changed file, leveraging composability. Mark Rochkind built on this idea to create the Source Code Control System (SCCS). Rather than storing a complete copy of every changed file, SCCS stored the original and a list of changes for each version. This allowed users to request any version of the file, which would get constructed on the fly.
SCCS had an awkward user interface, and it was slow because as revisions piled up, more sets of changes had to be applied to reconstruct a version. Walter Tichy released Revision Control System (RCS) in 1982. RCS had a better user interface and used backward differencing instead of SCCS’s forward differencing, meaning that RCS kept the most recent version and the changes needed to generate older versions. Since the current version was mostly what users wanted, it was much faster.
SCCS and RCS only worked well on a single computer. Dick Grune developed the Concurrent Versioning System (CVS), which essentially provided network access to RCS-like functionality in addition to being the first system to use merges instead of locks.
The original SCCS and RCS tools didn’t scale well because they relied on file locking; users would “check out” a file, edit it, and then “check in.” A checked-out file couldn’t be edited by others. This was especially problematic if someone locked a file and went on vacation. In response to this limitation, distributed systems such as Subversion, Bitkeeper, and Git were created. These tools replace the lock problem with the merge problem. Anyone can edit files, but they must reconcile their changes with changes made by others when checking back in.
Use one of these programs to track your code. RCS is very simple and easy to use if you’re just working on a project by yourself on your own system. Right now, Git is the most popular for distributed projects. Learn it.
Testing
Section titled “Testing”You can’t really know if a program is working unless you test it. Develop a set of tests along with your program. (Some methodologies espouse starting with the tests.) Keep the tests under source control. Again, one of the great
things about UNIX automation is that you can craft a single command that fires off a complete batch of tests. It’s often useful to do a nightly build, where the program build is started at a particular time every day and tests are run. Regression testing is a term used to describe the process of verifying that code changes didn’t break anything that used to work. Regress in this context means “to go backward”; regression testing helps to make sure that fixed bugs aren’t reintroduced.
Several programs are available to help you do testing. While it’s complicated, there are frameworks that allow you to test user interfaces by programmatically typing and clicking.
Where possible, have someone else also generate tests for your code. It’s natural for the person writing the code to be subconsciously blind to known problems and to avoid writing tests for them.
Bug Reporting and Tracking
Section titled “Bug Reporting and Tracking”Users will find bugs in your code independent from your own testing. You need some way for them to report bugs and some way to track how and whether those bugs were fixed.
Again, there are many tools available to support this.
Refactoring
Section titled “Refactoring”Refactoring is the process of rewriting code without changing the behavior or interfaces. It’s sort of like fast prototyping slowly. Why would you do this? Primarily because when the code was fully fleshed out, it became a mess and you think you know how to do it better. Refactoring can reduce maintenance costs. However, you need a good set of tests to make sure that the refactored code works like it’s supposed to. Also, any time things are being rewritten, there’s a temptation to add new features—don’t give in to it. Refactoring is a good time to reexamine the principles behind what’s already been done as mentioned earlier in “Fast Prototyping” on page 432.
Maintenance
Section titled “Maintenance”One programming fact that’s not obvious is that for any serious piece of code, the cost of maintenance greatly exceeds the cost of development. Keep this in mind. Avoid doing cute twisty things that might impress your peers. Remember that if people doing maintenance were as smart as you, they’d be doing design, not maintenance.
In Chapter 12, you saw several different ways to write asynchronous JavaScript code. Some of these ways keep everything in one place, while others separate setup from execution. It takes longer for maintainers to find and fix bugs when they have to track down all of the pieces.
Some programmers believe that a program is a work of art that must be understood in its fullness before being touched. This is a great-sounding philosophy. But in reality, it’s more important that someone be able to look
at any part of the code and quickly understand what it does. Writing beautiful code that can’t be maintained often leads to failure. Find the beauty in making code that’s easy to understand.
Something that really helps maintainers if your code talks to hardware is to include references to the hardware datasheets in your code. If you’re poking at some register, include the datasheet page number(s) where that register is described.
Be Stylish
Section titled “Be Stylish”People often learn about programming without understanding the environment in which it exists. There are a few things to keep in mind here.
You may not have thought too much about the educational system. Right now it’s spewing knowledge at you, some of which you’ll actually absorb. Where did this knowledge come from? Other people discovered it. At some point, especially if you pursue an advanced degree, it’ll be your turn to discover things that other people will learn. One of the great things about open source software projects is that you can contribute to them. Even if you’re not ready to code, many of these projects need help with documentation, so if there’s some program that you use or that interests you, get involved. It’s a great way to meet people, and it also looks good on college and job applications. Be cautious, as many programmers are not particularly adept socially. Have a thick skin.
When you write software, write it clearly and document it well. Make sure that others can understand what’s going on, or nobody will be able to help you. Get your “job security” by garnering a reputation for doing good work instead of by making sure that nobody but you can work on your code. Again, bear in mind that, as I said before, the cost of maintaining software greatly exceeds the cost of development.
Where possible, make your software open source. Give back to the body of work on which you rely.
Learn to write coherent, correctly spelled English (or the human language of your choice). Write real documentation for your code. Avoid documentation-generating tools such as Doxygen. You may have noticed that those are wonderful tools for generating large volumes of worthless documentation.
Documentation needs to describe what the code is doing. It should illuminate the structure of the data and how it is manipulated by the code. My first job writing code was at Bell Telephone Laboratories when I was in high school. Lucky me! My boss told me that every line of code should be commented. Not being very smart at the time, I did things like this:
lda foo ; load foo into the accumulatoradd 1 ; add 1sta foo ; store the result back in fooAs you can probably see, these comments were completely worthless. It would have been better to say something like:
; foo contains the number of gremlins hiding in the corner. ; Bump the count because we just found another. lda foo add 1 sta foo
Way back in 1985, I had the idea that it would be cool to be able to extract documentation from source code files, especially because you could change the documentation in the same place where you were changing the code. I wrote a tool called *xman* (extract manual) that generated troff-format typeset manuals from the source code. It used a special C comment that began with `/**` to introduce documentation. On a different world-track, my proposal to teach a course at the 1986 SIGGRAPH conference was accepted. I needed some additional speakers and contacted James Gosling, later an inventor of Java. I demonstrated xman for him. A short time later, we abandoned xman because it became clear that, while it could produce lots of pretty documentation, it was the wrong type of documentation. While correlation does not demonstrate causation (and Gosling doesn’t remember), Java included *Javadoc*, a way to include documentation in source files, and documentation was introduced by `/**` comments. This technique was copied by many other tools. So maybe I’m responsible for this mess.
When you look at automatically generated documentation, it tends to be of the “add 1” variety. There are volumes of documentation that contain only function names, plus the names and types of the arguments. If you can’t figure this out just by glancing at the code, you shouldn’t be programming! Little of this documentation says what the function does, how it does it, and how it relates to the rest of the system. The moral is, don’t be fooled into thinking that fancy tools are the same thing as good documentation. Write good documentation.
One last comment on documentation: include things that are obvious to you, the things that you don’t think about at all. People reading your documentation don’t know the things that are obvious to you. There is a famous comment in UNIX version 6—which had few comments—that said, “You are not expected to understand this.” Not the most helpful!
## Fix, Don’t Re-create
The software universe, especially the open source part, is littered with partially working programs and programs that do many but not all of the same things. Avoid this type of behavior.
Try to finish both your own projects and those started by others. If you don’t finish yours, at least leave them in good enough shape that someone else can easily take over the development. Remember, it’s about adding value.
<!-- page: 484 (printed 444) -->
# Summary
Now you’ve learned that programming involves more than just knowing about hardware and software. It’s a complex and rewarding endeavor that requires a lot of disparate knowledge. We’ve covered a lot of ground together. You’ve seen how to represent and operate on complex information using bits. You’ve learned why we use bits and how we build them in hardware. We’ve explored fundamental hardware building blocks and how to assemble those blocks into computers. We looked at the additional functionality needed to make computers more usable and various technologies for connecting computers to the outside world. This was followed by a discussion of how to organize data to take advantage of memory architectures. We looked at the process for converting computer languages into instructions that the hardware can understand. You learned about web browsers and how they organize data and process languages. High-level applications were compared to lower-level system programs. A number of interesting tricks for solving problems were examined, along with a lot of cat pictures. Some of the issues resulting from multitasking were discussed. We looked at the advanced topics of security and machine intelligence, which involved even more cats. Hopefully you noticed that the fundamental building blocks and tricks are used again and again in different combinations. Finally, you learned that the task of programming involves people in addition to hardware and software.
This is all just the beginning. It puts what you’ve learned or are learning about programming into perspective and gives you a foundation. Don’t stop here; there is much, much more to learn.
You might recall that way back in the book’s introduction I mentioned the need to understand the universe. It’s not possible for any one person to understand everything about the universe. One of the parts that I’ve never been able to figure out is how to nicely end a book. So that’s it. We’re done. The end.