- Transaction Script
- Domain Model
- Table Module
- Service Layer
Table Module
A single instance that handles the business logic for all rows in a database table or view.
One of the key messages of object orientation is bundling the data with the behavior that uses it. The traditional object-oriented approach is based on objects with identity, along the lines of Domain Model (116). Thus, if we have an Employee class, any instance of it corresponds to a particular employee. This scheme works well because once we have a reference to an employee, we can execute operations, follow relationships, and gather data on him.
One of the problems with Domain Model (116) is the interface with relational databases. In many ways this approach treats the relational database like a crazy aunt who's shut up in an attic and whom nobody wants to talk about. As a result you often need considerable programmatic gymnastics to pull data in and out of the database, transforming between two different representations of the data.
A Table Module organizes domain logic with one class per table in the database, and a single instance of a class contains the various procedures that will act on the data. The primary distinction with Domain Model (116) is that, if you have many orders, a Domain Model (116) will have one order object per order while a Table Module will have one object to handle all orders.
How It Works
The strength of Table Module is that it allows you to package the data and behavior together and at the same time play to the strengths of a relational database. On the surface Table Module looks much like a regular object. The key difference is that it has no notion of an identity for the objects it's working with. Thus, if you want to obtain the address of an employee, you use a method like anEmployeeModule.getAddress(long employeeID). Every time you want to do something to a particular employee you have to pass in some kind of identity reference. Often this will be the primary key used in the database.
Usually you use Table Module with a backing data structure that's table oriented. The tabular data is normally the result of a SQL call and is held in a Record Set (508) that mimics a SQL table. The Table Module gives you an explicit method-based interface that acts on that data. Grouping the behavior with the table gives you many of the benefits of encapsulation in that the behavior is close to the data it will work on.
Often you'll need behavior from multiple Table Modules in order to do some useful work. Many times you see multiple Table Modules operating on the same Record Set (508) (Figure 9.4).
The most obvious example of Table Module is the use of one for each table in the database. However, if you have interesting queries and views in the database you can have Table Modules for them as well.
The Table Module may be an instance or it may be a collection of static methods. The advantage of an instance is that it allows you to initialize the Table Module with an existing record set, perhaps the result of a query. You can then use the instance to manipulate the rows in the record set. Instances also make it possible to use inheritance, so we can write a rush contract module that contains additional behavior to the regular contract.
The Table Module may include queries as factory methods. The alternative is a Table Data Gateway (144), but the disadvantage of this is having an extra Table Data Gateway (144) class and mechanism in the design. The advantage is that you can use a single Table Module on data from different data sources, since you use a different Table Data Gateway (144) for each data source.
When you use a Table Data Gateway (144) the application first uses the Table Data Gateway (144) to assemble data in a Record Set (508). You then create a Table Module with the Record Set (508) as an argument. If you need behavior from multiple Table Modules, you can create them with the same Record Set (508). The Table Module can then do business logic on the Record Set (508) and pass the modified Record Set (508) to the presentation for display and editing using the table-aware widgets. The widgets can't tell if the record sets came directly from the relational database or if a Table Module manipulated the data on the way out. After modification in the GUI, the data set goes back to the Table Module for validation before it's saved to the database. One of the benefits of this style is that you can test the Table Module by creating a Record Set (508) in memory without going to the database.
The word “table” in the pattern name suggests that you have one Table Module per table in the database. While this is true to the first approximation, it isn't completely true. It's also useful to have a Table Module for commonly used views or other queries. Indeed, the structure of the Table Module doesn't really depend on the structure of tables in the database but more on the virtual tables perceived by the application, including views and queries.
When to Use It
Table Module is very much based on table-oriented data, so obviously using it makes sense when you're accessing tabular data using Record Set (508). It also puts that data structure very much in the center of the code, so you also want the way you access the data structure to be fairly straightforward.
However, Table Module doesn't give you the full power of objects in organizing complex logic. You can't have direct instance-to-instance relationships, and polymorphism doesn't work well. So, for handling complicated domain logic, a Domain Model (116) is a better choice. Essentially you have to trade off Domain Model (116)'s ability to handle complex logic against Table Module's easier integration with the underlying table-oriented data structures.
If the objects in a Domain Model (116) and the database tables are relatively similar, it may be better to use a Domain Model (116) that uses Active Record (160). Table Module works better than a combination of Domain Model (116) and Active Record (160) when other parts of the application are based on a common table-oriented data structure. That's why you don't see Table Module very much in the Java environment, although that may change as row sets become more widely used.
The most well-known situation in which I've come across this pattern is in Microsoft COM designs. In COM (and .NET) the Record Set (508) is the primary repository of data in an application. Record sets can be passed to the UI, where data-aware widgets display information. Microsoft's ADO libraries give you a good mechanism to access the relational data as record sets. In this situation Table Module allows you to fit business logic into the application in a well-organized manner, without losing the way the various elements work on the tabular data.
Example: Revenue Recognition with a Table Module (C#)
Time to revisit the revenue recognition example (page 112) I used in the other domain modeling patterns, this time with a Table Module. To recap, our mission is to recognize revenue on orders when the rules vary depending on the product type. In this example we have different rules for word processors, spreadsheets, and databases.
Table Module is based on a data schema of some kind, usually a relational data model (although in the future we may well see an XML model used in a similar way). In this case I'll use the relational schema from Figure 9.6.
The classes that manipulate this data are in pretty much the same form; there's one Table Module class for each table. In the .NET architecture a data set object provides an in-memory representation of a database structure. It thus makes sense to create classes that operate on this data set. Each Table Module class has a data member of a data table, which is the .NET system class corresponding to a table within the data set. This ability to read a table is common to all Table Modules and so can appear in a Layer Supertype (475).
class TableModule... protected DataTable table; protected TableModule(DataSet ds, String tableName) { table = ds.Tables[tableName]; }
The subclass constructor calls the superclass constructor with the correct table name.
class Contract... public Contract (DataSet ds) : base (ds, "Contracts") {}
This allows you to create a new Table Module just by passing in a data set to Table Module's constructor
contract = new Contract(dataset);
which keeps the code that creates the data set away from the Table Modules, following the guidelines of ADO.NET.
A useful feature is the C# indexer, which gets to a particular row in the data table given the primary key.
class Contract... public DataRow this [long key] { get { String filter = String.Format("ID = {0}", key); return table.Select(filter)[0]; } }
The first piece of functionality calculates the revenue recognition for a contract, updating the revenue recognition tables accordingly. The amount recognized depends on the kind of product we have. Since this behavior mainly uses data from the contract table, I decided to add the method to the contract class.
class Contract... public void CalculateRecognitions (long contractID) { DataRow contractRow = this[contractID]; Decimal amount = (Decimal)contractRow["amount"]; RevenueRecognition rr = new RevenueRecognition (table.DataSet); Product prod = new Product(table.DataSet); long prodID = GetProductId(contractID); if (prod.GetProductType(prodID) == ProductType.WP) { rr.Insert(contractID, amount, (DateTime) GetWhenSigned(contractID)); }else if (prod.GetProductType(prodID) == ProductType.SS) { Decimal[] allocation = allocate(amount,3); rr.Insert(contractID, allocation[0], (DateTime) GetWhenSigned(contractID)); rr.Insert(contractID, allocation[1], (DateTime) GetWhenSigned(contractID).AddDays(60)); rr.Insert(contractID, allocation[2], (DateTime) GetWhenSigned(contractID).AddDays(90)); }else if (prod.GetProductType(prodID) == ProductType.DB) { Decimal[] allocation = allocate(amount,3); rr.Insert(contractID, allocation[0], (DateTime) GetWhenSigned(contractID)); rr.Insert(contractID, allocation[1], (DateTime) GetWhenSigned(contractID).AddDays(30)); rr.Insert(contractID, allocation[2], (DateTime) GetWhenSigned(contractID).AddDays(60)); }else throw new Exception("invalid product id"); } private Decimal[] allocate(Decimal amount, int by) { Decimal lowResult = amount / by; lowResult = Decimal.Round(lowResult,2); Decimal highResult = lowResult + 0.01m; Decimal[] results = new Decimal[by]; int remainder = (int) amount % by; for (int i = 0; i < remainder; i++) results[i] = highResult; for (int i = remainder; i < by; i++) results[i] = lowResult; return results; }
Usually I would use Money (488) here, but for variety's sake I'll show this using a decimal. I use an allocation method similar to the one I use for Money (488).
To carry this out, we need some behavior that's defined on the other classes. The product needs to be able to tell us which type it is. We can do this with an enum for the product type and a lookup method.
public enum ProductType {WP, SS, DB}; class Product... public ProductType GetProductType (long id) { String typeCode = (String) this[id]["type"]; return (ProductType) Enum.Parse(typeof(ProductType), typeCode); }
GetProductType encapsulates the data in the data table. There's an argument for doing this for all columns of data, as opposed to accessing them directly as I did with the amount on the contract. While encapsulation is generally a Good Thing, I don't use it here because it doesn't fit with the assumption of the environment that different parts of the system access the data set directly. There's no encapsulation when the data set moves over to the UI, so column access functions only make sense when there's some additional functionality to be done, such as converting a string to a product type.
This is also a good time to mention that, although I'm using an untyped data set here because these are more common on different platforms, there's a strong argument (page 509) for using .NET's strongly typed data set.
The other additional behavior is inserting a new revenue recognition record.
class RevenueRecognition... public long Insert (long contractID, Decimal amount, DateTime date) { DataRow newRow = table.NewRow(); long id = GetNextID(); newRow["ID"] = id; newRow["contractID"] = contractID; newRow["amount"] = amount; newRow["date"]= String.Format("{0:s}", date); table.Rows.Add(newRow); return id; }
Again, the point of this method is less to encapsulate the data row and more to have a method instead of several lines of code that are repeated.
The second piece of functionality is to sum up all the revenue recognized on a contract by a given date. Since this uses the revenue recognition table it makes sense to define the method there.
class RevenueRecognition... public Decimal RecognizedRevenue (long contractID, DateTime asOf) { String filter = String.Format("ContractID = {0}AND date <= #{1:d}#", contractID,asOf); DataRow[] rows = table.Select(filter); Decimal result = 0m; foreach (DataRow row in rows) { result += (Decimal)row["amount"]; } return result; }
This fragment takes advantage of the really nice feature of ADO.NET that allows you to define a where clause and then select a subset of the data table to manipulate. Indeed, you can go further and use an aggregate function.
class RevenueRecognition... public Decimal RecognizedRevenue2 (long contractID, DateTime asOf) { String filter = String.Format("ContractID = {0}AND date <= #{1:d}#", contractID,asOf); String computeExpression = "sum(amount)"; Object sum = table.Compute(computeExpression, filter); return (sum is System.DBNull) ? 0 : (Decimal) sum; }