Most applications will need to access persistent data at some point, which may reside in relational databases, flat files, mainframe systems, LDAP repositories, or be provided by services through external systems. When business components need to access a data source, they need to use the appropriate mechanism to achieve connectivity and manipulate the stored data. Mechanisms to access these different types of persistent storage differ greatly, often incorporating proprietary APIs; access mechanisms for different data sources rarely have much in common. For example, accessing a relational database in Java requires using the JDBC API – this API cannot be used in many circumstances other than accessing a relational database.
Usage of these different access mechanisms can potentially create a direct dependency between business logic and data access code. If a business module relies on the internal workings or implementation of a data access module, or if the business module directly includes some aspects of the connectivity and data access code, a tight coupling is created between the business and data logic, directly affecting the portability of each.
The following diagram illustrates the structure of a typical application which accesses persistent data stored in a relational database. The data logic and JDBC API are embedded to some degree within the business logic, tightly coupling the two layers together.
Figure 1 - Typical Application Structure
Tight coupling between modules will produce a number of difficulties and issues:
• Changes in one module will potentially force a ripple of changes in the other module
• Modules will be more difficult to understand in isolation
• Modules will be difficult to reuse or test because all dependent modules must be included
With specific regard to a tight coupling between business and data logic, the code dependency will also make it difficult and tedious to migrate the application from one type of data source to another. If the data source changes, the business components will also need to be changed to handle the new data source.
Industry Design Patterns
Design patterns are general, repeatable solutions to commonly occurring development and design issues. Usage of design patterns helps to prevent issues that can cause major problems, improves code readability for developers familiar with the patterns, and speeds development and design processes by using proven solutions rather than creating a possibly flawed custom solution. Two commonly-used design patterns exist which are meant to decouple the business and data layers: the Data Access Object (DAO) and Factory patterns.
Data Access Object
A Data Access Object encapsulates all access to a persistent data store, providing a uniform API to its clients (usually business modules) as an interface. The interface only defines the general access methods that will be accessible to the clients, not the specific implementation of...