Home > Articles > Data

This chapter is from the book

Building Good Specifications

You could specify many different kinds of things with tests in any given software development endeavor. You could specify structures, public interfaces or private constructs, or what’s in a class. In database terms, you could specify tables, views, and stored procedures.

A test should specify behavior, but should not specify structure. The more behavior-focused a test is, the better off you will be because structures tend to change a lot more quickly than behaviors. This is true even in the database world where, frankly, the pace of change is nigh unto glacial. If you object to my use of the word quickly, you can think of it this way: Structures change a lot less slowly than behaviors in a database design.

However, tests have to couple to something in order to invoke the behaviors they define. In fact, many structure decisions are involved in making a test pass. The key is to drive those design decisions into a class of databases from the outside, not the other way around.

Specify Behavior, Not Structure

The odds that you are not a software developer are extremely low. My suspicion is that many of the readers of this book are accomplished computer programmers who also do database work and want to learn how to do what they already know how to do in a database domain. You might also be someone who works only or primarily on databases.

The chance also exists that you are an extraterrestrial archeologist sifting through the intellectual ruins of a species long-since turned to dust. If so, I hope I just sent a shiver up whatever your equivalent of a spine is. Also: Hello, and sorry we didn’t survive long enough for our paths to cross—unless you exterminated us, in which case I’m sorry our paths crossed and I hope you caught some horrible disease from us in the process.

Database programmers and application programmers are both still programmers. Both groups are responsible for writing software, which itself is an act of prescribing behaviors and relationships. In the case of object-oriented programming, what those things mean is pretty clear. At least, it is pretty clear now; it might not have been decades ago.

In the case of database development, it’s a little less intuitive what the behaviors being defined are. People often want to think of databases as collections of tables and relationships. The good thing about that is the focus on a database’s primary responsibility: storing stuff. Yet, it’s still a structure-oriented way of considering design.

A table is a bundle of related features tied to a kind of data. The two basic behaviors a table supports are data manipulation and data querying. Other structures carry with them other behaviors and certain platforms offer extra behaviors with various structures.

Those are what you should specify in tests. Don’t specify that there is a table. Specify that you can store and retrieve data of an interesting sort. Don’t specify that there is a view; specify that you can perform useful searches across bodies of data. That decision might seem meaningless now, but as the book proceeds it will become more and more valuable to you.

Drive Design In from Without, Not the Other Way Around

In the procedural days, entities were just data—purely passive things subject to the whims of whatever function might have access to them. With the advent of object-oriented design, they became reactive things that told the world what they could do and then waited for instructions. Modern development practices make classes of objects into servants, told what they should be able to do by tests and then told to do it by other objects and, ultimately, by people.

When you write a test, you want it to specify the behaviors that live in a class of databases, but it’s going to have to talk to something to do that. An implication of specifying a behavior is that you must also specify the minimal amount of public interface required to invoke that behavior. The key to discovering that is to learn it from writing tests first.

Let’s consider a problem. Imagine I need to write an application that keeps a database of streets and cross references them with other intersecting streets. I could drive the requirements from tests, specifying behaviors and required interface, or I could define my design inside out—starting with capabilities, then building an interface around it. I’ll try the latter first.

Defining the Design Inside Out

Well, the obvious thing I need is a table in which to store streets. So let’s start there (see Figure 3.1).

Figure 3.1

Figure 3.1. Simple design

Of course, streets exist in cities, so I need a cities table. Maybe later I’ll need a states table, too, but for now, I can live without it. Let’s add a cities table with a state column so I can track which street I am dealing with (see Figure 3.2).

Figure 3.2

Figure 3.2. Streets segregated by city

Some streets span many cities, such as highways and interstate freeways. So I need to account for those, too (see Figure 3.3).

Figure 3.3

Figure 3.3. A street going through multiple cities

Now there’s the fact that I need to track the intersections, so let’s add that. It seems like it should be a cross-reference table with the address on each street at which the intersection takes place. Because streets sometimes cross in multiple places, I need a primary key that is distinct from the foreign keys on that table so I can support multiple links, as shown in Figure 3.4.

Figure 3.4

Figure 3.4. Streets organized by city and cross-referenced by intersection

From there, I can start hypothesizing how the data might be used, adding views and stored procedures to support those needs. Then, I could write tests for all the behaviors I developed. Eventually, I’ll think I have enough to start writing an application.

Of course, I won’t.

For one thing, there is a distinct database for every city supported by the application. So, every application is encumbered by adding noise structures. The Cities and StreetToCityLinks tables are completely unnecessary as are the constraints surrounding them.

Also, the application doesn’t care where two streets connect, only that they connect. So, the Street1Address and Street2Address fields of the Intersections table serve no purpose but to waste the time of everyone who touches them or reads about them.

Defining the Design Outside In

What if I try going the other direction? Suppose I want to start at the outside and work my way inward. In that event, by the time I’m defining a database design, I probably would have written the user interface and application logic already.

Having done those things would provide me with context and understanding as to what was really needed. If I work exclusively with the database, then someone else would provide the context for me and I would have a very clear idea of what the requirements are.

Either way, that understanding would be something that could be translated into tests as in the following:

[Test]
public void CreateAndFindStreet() {
  connection.ExecuteSql("INSERT INTO Streets VALUES(5, 'Fun St.')");

  var id = connection.ExecuteScalar(
    "SELECT ID FROM Streets WHERE NAME LIKE '%Fun%'");

  Assert.That(id, Is.EqualTo(5));
}

That test would drive me to build a database class as follows:

<Database>
  <Version Number="1">
    <Script>
      <![CDATA[
CREATE TABLE Streets(ID INT PRIMARY KEY, NAME NVARCHAR(4000))
    </Script>
  </Version>
</Database>

Knowing that I also needed the capability to find related streets, I might write another test as follows:

[Test]
public void CreateConnectedStreetsAndFindFewestIntersectionsConnected()
{
  connection.ExecuteSql("INSERT INTO Streets VALUES(1, 'A St.')");
  connection.ExecuteSql("INSERT INTO Streets VALUES(2, 'B Dr.')");
  connection.ExecuteSql("INSERT INTO Streets VALUES(3, 'C Ave.')");
  connection.ExecuteSql("INSERT INTO Streets VALUES(4, 'D Ln.')");
  connection.ExecuteSql("INSERT INTO Streets VALUES(5, 'E Blvd.')");

  connection.ExecuteSql("INSERT INTO Intersections VALUES(1)");
  connection.ExecuteSql("INSERT INTO IntersectionStreets VALUES(1, 1)");
  connection.ExecuteSql("INSERT INTO IntersectionStreets VALUES(1, 2)");

  connection.ExecuteSql("INSERT INTO Intersections VALUES(2)");
  connection.ExecuteSql("INSERT INTO IntersectionStreets VALUES(2, 1)");
  connection.ExecuteSql("INSERT INTO IntersectionStreets VALUES(2, 3)");

  connection.ExecuteSql("INSERT INTO Intersections VALUES(3)");
  connection.ExecuteSql("INSERT INTO IntersectionStreets VALUES(3, 3)");
  connection.ExecuteSql("INSERT INTO IntersectionStreets VALUES(3, 4)");
  var result = connection.ExecuteScalar(
    "SELECT Depth FROM Connections() WHERE StartID = 2 AND EndID = 4");

  Assert.That(result, Is.EqualTo(3));
}

That test would drive me to develop the design in the next snippet:

<Database>
  <Version Number="1">
    <Script>
      <![CDATA[
CREATE TABLE Streets(ID INT PRIMARY KEY, NAME NVARCHAR(4000))
CREATE TABLE Intersections([ID] INT PRIMARY KEY)
CREATE TABLE IntersectionStreets(
  [IntersectionID] INT FOREIGN KEY REFERENCES Intersections(ID),
  [StreetID] INT FOREIGN KEY REFERENCES Streets(ID))
  ]]>
    </Script>
    <Script>
      <![CDATA[
CREATE VIEW ImmediateConnections AS
SELECT s.StreetID AS StartID, e.StreetID AS EndID
FROM IntersectionStreets AS s
INNER JOIN IntersectionStreets AS e
ON s.IntersectionID = e.IntersectionID and s.StreetID <> e.StreetID
      ]]>
    </Script>
    <Script>
      <![CDATA[
CREATE FUNCTION Connections
     (
     )
RETURNS @Result TABLE (Depth INT, StartID INT, EndID INT)
AS
BEGIN
  DECLARE @Temp TABLE (StartID INT, EndID INT)
  DECLARE @Depth INT
  SET @Depth = 0

  INSERT INTO @Temp SELECT ID AS StartID, ID AS EndID FROM Streets;

  WHILE EXISTS (SELECT TOP 1 * FROM @Temp)
  BEGIN
    INSERT INTO @Result SELECT @Depth, StartID, EndID FROM @Temp;
    DELETE @Temp;

    INSERT INTO @Temp SELECT r.StartID, ic.EndID FROM @Result AS r
      INNER JOIN ImmediateConnections AS ic ON r.EndID = ic.StartID

    DELETE @Temp FROM @Temp AS tc INNER JOIN @Result AS r
      ON tc.StartID = r.StartID AND tc.EndID = r.EndID

    SET @Depth = @Depth + 1
  END;
RETURN
END
      ]]>
    </Script>
  </Version>
</Database>

Note how narrow and focused the interface for the database that was designed outside-in is compared to the one that was designed inside-out. Yet, in certain areas such as the recursive view, the behavior is much deeper than with the inside-out design. The two side-effects of driving design into a system rather than designing a system and making clients find a way to use it are that you write something that can actually be used, and you spend more of your time developing worthwhile functionality.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020