Excerpt from ASP.NET MVC Framework Unleashed [con't]
What Is Good Software?
I dropped out of graduate school at MIT to launch an Internet startup in the earliest days of the Web. At that time, building a website was difficult. This was before technologies such as Active Server Pages or ASP.NET existed. (We had only stone knives.) Saving the contents of an HTML form to a database table was a major accomplishment. Blinking text was the height of cool.
When I first started writing software, simply getting the software to do what I wanted was the goal. Adding as many features to a website in the shortest amount of time was the key to survival in the ferociously competitive startup world of the ’90s. I used to sleep in my office under my desk.
During my startup phase, I would define good software like this:
If I was feeling particularly ambitious, I would worry about performance. And maybe, just maybe, if I had extra time, I would add a comment or two to my code. But really, at the end of the day, my criterion for success was simply that the software worked.
For the past 8 years, I’ve provided training and consulting to large companies and organizations such as Boeing, NASA, Lockheed Martin, and the National Science Foundation. Large organizations are not startups. In a large organization, the focus is not on building software applications as fast as possible; the focus is on building software applications that can be easily maintained over time.
Over the years, my definition of good software has shifted substantially. As I have been faced with the scary prospect of maintaining my own monsters, I’ve changed my definition of good software to this:
Good software is software that works as you intended and that is easy to change.
There are many reasons that software changes over time. Michael Feathers, in his excellent book Working Effectively with Legacy Code, offers the following reasons:
You might need to add a new feature to existing software.
You might need to fix a bug in existing software.
You might need to optimize existing software.
You might need to improve the design of existing software.
For example, you might need to add a new feature to an application. The call manager application started as a Single Button Application. However, each day, more and more features were added to the application.
You also need to change software when you discover a bug in the software. For instance, in the case of the call manager, we discovered that it did not calculate daylight savings time correctly. (It was waking some people up in the morning!) We rushed to change the broken code.
You also might need to modify a software application to make the application run faster. At one point, the call manager application took as long as 12 seconds to dial a new phone number. The business rules were getting complex. We had to rewrite the code to get the phone number retrieval time down to the millisecond range.
Finally, you might need to modify software to improve its design. In other words, you might need to take badly written code and convert it into good code. You might need to make your code more resilient to change.
Avoiding Code Smells
Unless you are careful, a software application quickly becomes difficult to change. We all have had the experience of inheriting an application that someone else has written and being asked to modify it. Think of the fear that strikes your heart just before you make your first change.
In the game of Pick-Up Sticks, you must remove stick after stick from a pile of sticks without disturbing the other sticks. The slightest mistake and the whole pile of sticks might scatter.
Modifying an existing software application is similar to the game of Pick-Up Sticks. You bump the wrong piece of code and you introduce a bug.
Bad software is software that is difficult to change. Robert and Micah Martin describe the markers of bad software as code smells. The following code smells indicate that software is badly written:
Rigidity—Rigid software is software that requires a cascade of changes when you make a change in one place.
Fragility—Fragile software is software that breaks in multiple places when you make a change.
Needless complexity—Needlessly complex software is software that is overdesigned to handle any possible change.
Needless repetition—Needlessly repetitious software contains duplicate code.
Opacity—Opaque software is difficult to understand.
Notice that these code smells are all related to change. Each of these code smells is a barrier to change.
Software Design Principles
Software does not need to be badly written. A software application can be designed from the beginning to survive change.
The best strategy for making software easy to change is to make the components of the application loosely coupled. In a loosely coupled application, you can make a change to one component of an application without making changes to other parts.
Over the years, several principles have emerged for writing good software. These principles enable you to reduce the dependencies between different parts of an application. These software principles have been collected together in the work of Robert Martin (AKA Uncle Bob).
Robert Martin did not invent all the principles; however, he was the first one to gather the principles into a single list. Here is his list of software design principles:
SRP—Single Responsibility Principle
OCP—Open Closed Principle
LSP—Liskov Substitution Principle
ISP—Interface Segregation Principle
DIP—Dependency Inversion Principle
This collection of principles is collectively known by the acronym SOLID. (Yes, SOLID is an acronym of acronyms.)
For example, according to the Single Responsibility Principle, a class should have one, and only one, reason to change. Here’s a concrete example of how this principle is applied: If you know that you might need to modify your application’s validation logic separately from its data access logic, then you should not mix validation and data access logic in the same class.
Software Design Patterns
Software design patterns represent strategies for applying software design principles. In other words, a software design principle is a good idea and a software design pattern is the tool that you use to implement the good idea. (It’s the hammer.)
The idea behind software design patterns was originally promoted by the book Design Patterns: Elements of Reusable Object-Oriented Software. (This book is known as the Gang of Four book.) This book has inspired many other books that describe software design patterns.
The Head First Design Pattern book provides a more user-friendly introduction to the design patterns from the Gang of Four book. The Head First Design book devotes chapters to 14 patterns with names like Observer, Façade, Singleton, and Adaptor.
Another influential book on software design patterns is Martin Fowler’s book Patterns of Enterprise Application Architecture. This book has a companion website that lists the patterns from the book: http://www.martinfowler.com/eaaCatalog.
Software design patterns provide you with patterns for making your code more resilient to change. For example, in many places in this book, we take advantage of a software design pattern named the Repository pattern. Eric Evans, in his book Domain-Driven Design, describes the Repository pattern like this:
“A REPOSITORY represents all objects of a certain type as a conceptual set (usually emulated). It acts like a collection, except with more elaborate querying capability. Objects of the appropriate type are added and removed, and the machinery behind the REPOSITORY inserts them or deletes them from the database.”
According to Evans, one of the major benefits of the Repository pattern is that it enables you to “decouple application and domain design from persistence technology, multiple database strategies, or even multiple data sources.” In other words, the Repository pattern enables you to shield your application from changes in how you perform database access.
For example, when we write our blog application at the end of this book, we take advantage of the Repository pattern to isolate our blog application from a particular persistence technology. The blog application will be designed in such a way that we could switch between different data access technologies such as LINQ to SQL, the Entity Framework, or even NHibernate.
Writing Unit Tests for Your Code
By taking advantage of software design principles and patterns, you can build software that is more resilient to change. Software design patterns are architectural patterns. They focus on the gross architecture of your application.
If you want to make your applications more change proof on a more granular level, then you can build unit tests for your application. A unit test enables you to verify whether a particular method in your application works as you intend it to work.
There are many benefits that result from writing unit tests for your code:
Building tests for your code provides you with a safety net for change.
Building tests for your code forces you to write loosely coupled code.
Building tests for your code forces you to take a user perspective on the code.
First, unit tests provide you with a safety net for change. This is a point that Michael Feathers emphasizes again and again in his book Working Effectively with Legacy Code. In fact, he defines legacy code as “simply code without tests.”
When your application code is covered by unit tests, you can modify the code without the fear that the modifications will break the functionality of your code. Unit tests make your code safe to refactor. If you can refactor, then you can modify your code using software design patterns and thus produce better code that is more resilient to change.
Second, writing unit tests for your code forces you to write code in a particular way. Testable code tends to be loosely coupled code. A unit test performs a test on a unit of code in isolation. To build your application so that it is testable, you need to build the application in such a way that it has isolatable components.
One class is loosely coupled to a second class when you can change the first class without changing the second class. Test-driven development often forces you to write loosely coupled code. Loosely coupled code is resistant to change.
Finally, writing unit tests forces you to take a user’s perspective on the code. When writing a unit test, you take on the same perspective as a developer who will use your code in the future. Because writing tests forces you to think about how a developer (perhaps, your future self) will use your code, the code tends to be better designed.
In the previous section, we discussed the importance of building unit tests for your code. Test-driven development is a software design methodology that makes unit tests central to the process of writing software applications. When you practice test-driven development, you write tests first and then write code against the tests.
More precisely, when practicing test-driven development, you complete three steps when creating code (Red/Green/Refactor):
Write a unit test that fails (Red).
Write code that passes the unit test (Green).
Refactor your code (Refactor).
First, you write the unit test. The unit test should express your intention for how you expect your code to behave. When you first create the unit test, the unit test should fail. The test should fail because you have not yet written any application code that satisfies the test.
Next, you write just enough code for the unit test to pass. The goal is to write the code in the laziest, sloppiest, and fastest possible way. You should not waste time thinking about the architecture of your application. Instead, you should focus on writing the minimal amount of code necessary to satisfy the intention expressed by the unit test.
Finally, after you write enough code, you can step back and consider the overall architecture of your application. In this step, you rewrite (refactor) your code by taking advantage of software design patterns—such as the Repository pattern—so that your code is more maintainable. You can fearlessly rewrite your code in this step because your code is covered by unit tests.
There are many benefits that result from practicing test-driven development. First, test-driven development forces you to focus on code that actually needs to be written. Because you are constantly focused on just writing enough code to pass a particular test, you are prevented from wandering into the weeds and writing massive amounts of code that you will never use.
Second, a “test first” design methodology forces you to write code from the perspective of how your code will be used. In other words, when practicing test-driven development, you constant write your tests from a user perspective. Therefore, test-driven development can result in cleaner and more understandable APIs.
Finally, test-driven development forces you to write unit tests as part of the normal process of writing an application. As a project deadline approaches, testing is typically the first thing that goes out the window. When practicing test-driven development, on the other hand, you are more likely to be virtuous about writing unit tests because test-driven development makes unit tests central to the process of building an application.
Short-Term Pain, Long-Term Gain
Building software designed for change requires more upfront effort. Implementing software design principles and patterns takes thought and effort. Writing tests takes time. However, the idea is that the initial effort required to build software the right way will pay huge dividends in the future.
There are two ways to be a developer. You can be a cowboy or you can be a craftsman. A cowboy jumps right in and starts coding. A cowboy can build a software application quickly. The problem with being a cowboy is that software must be maintained over time.
A craftsman is patient. A craftsman builds software carefully by hand. A craftsman is careful to build unit tests that cover all the code in an application. It takes longer for a craftsman to create an application. However, after the application is created, it is easier to fix bugs in the application and add new features to the application.
Most software developers start their programming careers as cowboys. At some point, however, you must hang up your saddle and start building software that can stand the test of time.