For an example somewhat extreme in its ideological purity:
First, an interface for classes that can retrieve objects of type T from the database given their ID:
interface IAdapter<T>
{
T Retrieve(int id);
}
Now, the Book
class, which no longer exposes a public constructor, but instead a static method that uses an IAdapter<Book>
to retrieve the book from the database:
public class Book
{
public static IAdapter<Book> Adapter { get; set; }
public static Book Create(int id)
{
return Adapter.Retrieve(id);
}
// constructor is internal so that the Adapter can create Book objects
internal Book() { }
public int ID { get; internal set; }
public string Title { get; internal set; }
public bool AvailableForCheckout { get; internal set; }
}
You have to write the class implementing IAdapter<Book>
yourself, and assign Book.Adapter
to an instance of it so that Book.Create()
will be able to pull things from the database.
I say "ideological purity" because this design enforces a pretty rigid separation of concerns: there's nothing in the Book
class that knows how to talk to the database - or even that there is a database.
For instance, here's one possible implementation of IAdapter<Book>
:
public class DataTableBookAdapter : IAdapter<Book>
{
public DataTable Table { get; set; }
private List<Book> Books = new List<Book>();
Book Retrieve(int id)
{
Book b = Books.Where(x => x.ID = id).FirstOrDefault();
if (b != null)
{
return b;
}
BookRow r = Table.Find(id);
b = new Book();
b.ID = r.Field<int>("ID");
b.Title = r.Field<string>("Title");
b.AvailableForCheckout = r.Field<bool>("AvailableForCheckout");
return b;
}
}
Some other class is responsible for creating and populating the DataTable
that this class uses. You could write a different implementation that uses a SqlConnection
to talk to the database directly.
You can even write this:
public IAdapter<Book> TestBookAdapter : IAdapter<Book>
{
private List<Book> Books = new List<Book>();
public TestBookAdapter()
{
Books.Add(new Book { ID=1, Title="Test data", AvailableForCheckout=false };
Books.Add(new Book { ID=2, Title="Test data", AvailableForCheckout=true };
}
Book Retrieve(int id)
{
return Books.Where(x => x.ID == id);
}
}
This implementation doesn't use a database at all - you'd use this when writing unit tests for the Book
class.
Note that both of these classes maintain a private List<Book>
property. This guarantees that every time you call Book.Create()
with a given ID, you get back the same Book
instance. There's an argument to be made for making this a feature of the Book
class instead - you'd make a static private List<Book>
property in Book
and write logic to make the Create
method maintain it.
You use the same approach for pushing data back to the database - add Update
, Delete
, and Insert
methods to IAdapter<T>
and implement them in your adapter classes, and have Book
call those methods at the appropriate time.