6.2. Design

A good design for our problem is to use the IRepository pattern. This is a simple but yet very powerful pattern that allows us to abstract the data layer from our code. Abstracting the data layer gives us a lot of flexibility in our design and simplifies our testing. Don't worry if all this sounds too theoretical right now — the next few pages will help clarify all the concepts.

In the previous chapter, we created an IMessageService interface that, so far, has only one method that adds a message to the database. The beauty of using the service layer is that the application code doesn't need to know anything about the underlying details of the what, how, and where of dealing with the database. It just knows that it needs to call the Add method and handle any validation exceptions. Using an interface at this layer makes our testing easier by giving us the ability to mock the interface and/or implement a test-specific implementation. We now take this same concept and abstract it one more layer. We will pass an IMessageRepository interface into the MessageService class; the IMessageRepository interface will deal strictly with working with the repository/database/data store. That's its single responsibility.

Let's think about what we need to do here. We want to basically perform CRUD (create, read, update, and delete) operations on the data, so our IRepository interface, at the least, needs to include these operations. Our class diagrams so far are shown in Figure 6-1

Get ASP.NET MVC 1.0 Test Driven Development: Problem - Design - Solution now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.