Four layers architecture
Architectural Decisions are all about trade-off referring to a specific context.
A Four Layers architecture address the connection of the domain to the outside world(i.e., object persistency mechanisms, network protocol, etc).
We factor our application classes into:
- The Presentation layer. Where the physical windows and widgets live. Any new user interface widgets are put in this layer. For example, the GWT Views live on this layer.
- The Application or Service layer. Mediate between the various user interface components an translate the messages into messages understood by the objects in the Domain Model.
- The Domain Model layer. Here reside all objects found in an OO analysis and design. These are the appropriate objects that solve our problem domain (domain objectare potentially available for reuse.)
- The Infrastructure layer. Objects that represent connections to entities outside the application. For example the Persistence layer connect to an underlining DBMS.
Service Layers
Service Layer defines an application's boundary with a layer of services that establishes a set of available operations and coordinates the application's response in each operation.
A Service Layer defines an application's boundary [Cockburn PloP] and its set of available operations from the perspective of interfacing client layers.
It encapsulates the application's business logic,
- controlling transactions and
- coordinating responses in the implementation of its operations.
Service Layer is a pattern for organizing business logic. Many designers like to divide business logic into two kinds:
- domain logic. Having to do purely with the problem domain (such as strategies for calculating revenue recognition on a contract), and
- application logic. Having to do with application responsibilities. Application logic is sometimes referred to as workflow logic.
Service Layer can be implemented in different way:
Implementation Variations
The two basic implementation variations are the domain
facade approach and the operation script approach.
In the domain facade approach a Service Layer is implemented as a set of thin facades over a Domain Model (116). The classes implementing the facades don't implement any business logic. Rather, the Domain Model (116) implements all of the busi-ness logic. The thin facades establish a boundary and set of operations through which client layers interact with the application, exhibiting the defining characteristics of Service Layer.
In the operation script approach a Service Layer is implemented as a set of thicker classes that directly implement application logic but delegate to encapsulated domain object classes for domain logic. The operations available to clients of a Service Layer are implemented as scripts, organized several to a class defining a subject area of related logic. Each such class forms an application “ser-
vice,†and it’s common for service type names to end with “Service.†A Service
Layer is comprised of these application service classes, which should extend a
Layer Supertype (475), abstracting their responsibilities and common behaviors.
To Remote or Not to Remote The interface of a Service Layer class is coarse
grained almost by definition, since it declares a set of application operations
available to interfacing client layers. Therefore, Service Layer classes are well
suited to remote invocation from an interface granularity perspective.
However, remote invocation comes at the cost of dealing with object distri-
bution. It likely entails a lot of extra work to make your Service Layer method
signatures deal in Data Transfer Objects (401). Don’t underestimate the cost of
this work, especially if you have a complex Domain Model (116) and rich edit-
ing UIs for complex update use cases! It’s significant, and it’s painful—perhaps
second only to the cost and pain of object-relational mapping. Remember the
First Law of Distributed Object Design (page 89).
My advice is to start with a locally invocable Service Layer whose method
signatures deal in domain objects. Add remotability when you need it (if ever)
by putting Remote Facades (388) on your Service Layer or having your Service
Layer objects implement remote interfaces. If your application has a Web-based
UI or a Web-services-based integration gateway, there’s no law that says your
business logic has to run in a separate process from your server pages and Web
services. In fact, you can save yourself some development effort and runtime
response time, without sacrificing scalability, by starting out with a colocated
approach.
Identifying Services and Operations Identifying the operations needed on a Ser-
vice Layer boundary is pretty straightforward. They’re determined by the needs
of Service Layer clients, the most significant (and first) of which is typically a
user interface. Since a user interface is designed to support the use cases that
actors want to perform with an application, the starting point for identifying
Service Layer operations is the use case model and the user interface design for
the application.
Disappointing as it is, many of the use cases in an enterprise application
are fairly boring “CRUD†(create, read, update, delete) use cases on domain
objects—create one of these, read a collection of those, update this other thing. My experience is that there’s almost always a one-to-one correspon-
dence between CRUD use cases and Service Layer operations.
The application’s responsibilities in carrying out these use cases, however,
may be anything but boring. Validation aside, the creation, update, or deletion
of a domain object in an application increasingly requires notification of other
people and other integrated applications. These responses must be coordinated,
and transacted atomically, by Service Layer operations.
If only it were as straightforward to identify Service Layer abstractions to
group related operations. There are no hard-and-fast prescriptions in this area;
only vague heuristics. For a sufficiently small application, it may suffice to have
but one abstraction, named after the application itself. In my experience larger
applications are partitioned into several “subsystems,†each of which includes a
complete vertical slice through the stack of architecture layers. In this case I prefer
one abstraction per subsystem, named after the subsystem. Other possibilities
include abstractions reflecting major partitions in a domain model, if these are
different from the subsystem partitions (e.g., ContractsService, ProductsService), and
abstractions named after thematic application behaviors (e.g., RecognitionService).
Java Implementation
In both the domain facade approach and the operation script approach, a
Service Layer class can be implemented as either a POJO (plain old Java
object) or a stateless session bean. The trade-off pits ease of testing against
ease of transaction control. POJOs might be easier to test, since they don’t
have to be deployed in an EJB container to run, but it’s harder for a POJO
Service Layer to hook into distributed container-managed transaction ser-
vices, especially in interservice invocations. EJBs, on the other hand, come
with the potential for container-managed distributed transactions but have
to be deployed in a container before they can be tested and run. Choose
your poison.
My preferred way of applying a Service Layer in J2EE is with EJB 2.0
stateless session beans, using local interfaces, and the operation script
approach, delegating to POJO domain object classes. It’s just so darned con-
venient to implement a Service Layer using stateless session bean, because of
the distributed container-managed transactions provided by EJB. Also, with
the local interfaces introduced in EJB 2.0, a Service Layer can exploit the
valuable transaction services while avoiding the thorny object distribution
issues.
On a related Java-specific note, let me differentiate Service Layer from
the Session Facade pattern documented in the J2EE patterns literature
[Alur et al.] and [Marinescu]. Session Facade was motivated by the desire to avoid the performance penalty of too many remote invocations on entity
beans; it therefore prescribes facading entity beans with session beans. Ser-
vice Layer is motivated instead by factoring responsibility to avoid duplica-
tion and promote reusability; it’s an architecture pattern that transcends
technology. In fact, the application boundary pattern [Cockburn PloP] that
inspired Service Layer predates EJB by three years. Session Facade may be
in the spirit of Service Layer but, as currently named, scoped, and presented,
is not the same.
When to Use It
The benefit of Service Layer is that it defines a common set of application oper-
ations available to many kinds of clients and it coordinates an application’s
response in each operation. The response may involve application logic that
needs to be transacted atomically across multiple transactional resources. Thus,
in an application with more than one kind of client of its business logic, and
complex responses in its use cases involving multiple transactional resources, it
makes a lot of sense to include a Service Layer with container-managed transac-
tions, even in an undistributed architecture.
The easier question to answer is probably when not to use it. You probably
don’t need a Service Layer if your application’s business logic will only have one
kind of client—say, a user interface—and its use case responses don’t involve
multiple transactional resources. In this case your Page Controllers can manu-
ally control transactions and coordinate whatever response is required, perhaps
delegating directly to the Data Source layer.
But as soon as you envision a second kind of client, or a second transactional
resource in use case responses, it pays to design in a Service Layer from the
beginning.
DTO: Data transfer object or Value Object
References: http://martinfowler.com/bliki/LocalDTO.html
DTO is a design pattern used to transfer data.
DTOs have only behaviour (accessors and mutators) for storage and retrieval of its own data.
DTOs are used to encapsulate the data between the Service Layerand the Presentation Layer
Different uses:
-
A good use of (Remote) DTOs is to transfer data in expensive remote calls. They are part of implementing a coarse grained interface which a remote interface needs for performance.
-
A potentially bad use of (Local) DTOs is to use them as part of a Service Layer API although this ensure that service layer clients aren't dependent upon an underlying Domain Model. As matter of fact there is a painful cost of data mapping perhaps second only to the cost of ORM. In this use case a proxy is created when you add a new Controller (or service!) reference will contain all of the DTO types. Presentation Layer can take DTOs and map them to very specific DTO's for each Page/Control concern.
We do you not need them in a local context (to transfer data between software application subsystems) because they are actually harmful:
-
a coarse-grained API is more difficult to use
-
you have to do all the work moving data from your domain or data source layer into the DTOs
-
A good use of (Local) DTOs is where it is when you have a significant mismatch between the model in your presentation layer and the underlying domain model. In this case it makes sense to make presentation specific facade/gateway that maps from the domain model and presents an interface that's convenient for the presentation. It fits in nicely with Presentation Model.
-
A !!!! use of (Local) DTOs as part of the presentation layer if they are view-specific. It should really be the controller's job to ensure that the View only gets from the Model what it needs – for example, a value-object with just the fields needed by the view.
-
A good use of (Local) DTOs is to communicate between isolates in multi-threaded applications. A good way to handle multi-threading is to partition your application into isolated areas where each area has only one thread running over it. This eliminates the needs for concurrency controls within that area. If you need to communicate between these isolated areas, then use a message queue with DTOs as messages to transfer the information.
In DDD approach it is best to have your infrastructure projects (such as a web-platform-specific UI) referencing your domain objects than vice versa.
With this approach our web project have a direct dependency on the project, having our rich domain objects depending on your web project.
DTOs in conjunction with DAOs are often used to retrieve data from a database.
In a traditional EJB architecture, DTOs serve dual purposes:
-
DTO are serializable;
-
implicitly define an assembly phase where all data to be used by the view are fetched and marshalled into the DTOs before returning control to the presentation tier.
Domain Model Layer
A domain model in problem solving and software engineering can be thought of as a conceptual model of a domain of interest (often referred to as a problem domain) which describes the various entities, their attributes and relationships, plus the constraints that govern the integrity of the model elements comprising that problem domain.
The domain model is created in order to represent the vocabulary and key concepts of the problem domain. The domain model also identifies the relationships among all the entities within the scope of the problem domain, and commonly identifies their attributes. A domain model that encapsulates methods within the entities is more properly associated with object oriented models. The domain model provides a structural view of the domain that can be complemented by other dynamic views, such as Use Case models.
An important advantage of a domain model is that it describes and
constrains the scope of the problem domain. The domain model can be
effectively used to verify and validate the understanding of the
problem domain among various stakeholders. It is especially helpful
as a communication tool and a focusing point both amongst the
different members of the business team as well as between the
technical and business teams.
Business object
Abusiness objectis a type of an intelligible entitybeing an actorinside the business layer.
A business object usually does nothing itself but holds:
-
attributes: set of instance variables or properties
-
associations with other business objects, weaving a map of objects representing the business relationships
Business The DAO pattern and the ActiveRecord pattern are quite distinct patterns for data access. The ActiveRecord pattern is characterized by a domain model that "knows" it is persistent - each entity class has a Save() method on it. In contrast, the entire point of the DAO pattern is that the entities do not know that they are persistent objects. This maintains a stricter separation of concerns. Each pattern has its advantages and disadvantages, but to merge the two articles, and lose the distinction between the two patterns, makes no sense. Compare Martin Fowler's articles on ActiveRecord[1] and DataMapper[2] (his name for DAO)objects separate state from behavior because they are communicated across the tiers in a multi-tiered system
Sometimes a relational entitycan be mapped by a business object but this is not a rule.
Although a business objectrepresents an entity, it should not be confused with relational model entities (Object relational . Take as example a relational entity like "Customer" which has a "Kind" attribute in order to distinguish "Country customers" from "Abroad customers". Because of design needs, maybe this relational entity will end in two business objects: "CountryCustomer" and "AbroadCustomer", since everyone will not hold same associations. First will be holding fiscal associations while second will be associated with taxes and its related duty.
An example of Business object would be a concept like "Process" having "Identifier", "Name", "Start date", "End date" and "Kind" attributes and holding an association with the "Employee" (the responsible) that started it.
A Domain Model creates a web of interconnected objects, where each object represents some meaningful individual, whether as large as a corporation or as small as a single line on an order form.
objects that model the business area you’re working in . A Domain Model mingles data and process,
Basically, there are two styles of Domain Model in the field.
A simple Domain Model looks very much like the database design with mostly one domain object for each database table.
A simple Domain Model can use Active Record.
Entity beans can’t be re-entrant. That is, if you call out from one entity bean into another object, that other object (or any object it calls) can’t call back into the first entity bean.
In my application I have pretty modest domain logic and than I used entity beansto develop a domain model. The entity beans are not re-entrant and implement the Active Record pattern.
A rich Domain Model can look different from the data- base design, with inheritance, strategies, and other [Gang of Four] patterns, and complex webs of small interconnected objects.
A rich Domain Model is better for more complex logic, but is harder to map to the database.
A rich Domain Model requires Data Mapper. This will help keep your Domain Model independent from the database and is the best approach to handle cases where the Domain Model and database schema diverge.
A rich Domain often uses re-entrancy.
A POJO domain model is easy to put together, is quick to build, can run and test out side an EJB container, and is independent of EJB .
A common concern with domain logic is bloated domain objects. For example as you build a screen to manipulate orders you’ll notice that some of the order behaviour is only neededonly for it. The problem with separating usage-specific behavioris that it can lead to duplication. Behavior that’s separated from the order is harder to find, so people tend to not see it and duplicate it instead . The advice is not to separate usage-specific behavior. Put it all in the object that’s the natural fit. Fix the bloating when, and if, it becomes a problem. Spring AOP comes in our help.
An object model of the domain that incorporates both behaviourand data.
Business Object implemented as a Anemic Domain Model
A domain model where business objects do not have behaviouris called an Anemic Domain Model.
The Anemic Domain Modelis a term used to describe the use of a software domain model where the business logicis implemented outside the domain objects.
Transaction scripts, the separated classes where the domain logic is implemented, transform the state of the domain objects.
This pattern is encouraged by technologies such as early versions of EJB's Entity Beans.
Domain Model or Transaction Script?
It all comes down to the complexity of the behaviour in your system. If you have complicated and everchanging business rules involving validation, calculations, and derivations, chances are that you’ll want an object model to handle them.
On the other hand, if you have simple not-null checks and a couple of sums to calculate, a Transaction Script is a better bet
Domain Model or Table Model?
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.
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 an EmployeeModule.getAddress(long employeeID). Every time you want to do some- thing to a particular employee you have to pass in some kind of identity reference.
Domain Models (116) are preferable to Transaction Scripts (110) for
avoid- ing domain logic duplication and for managing complexity using
classical design patterns.
Persisting Layer
DAO: Data access object or Data Mapper (Relational Entity)
It is an ORM entity. Sometimes is useful to implement a Relational entity using an Active Record Patternwhich simplify and make easy the use of CRUD operations into a Datastore
-
Active Record Pattern (Relational entity)
Active Record pattern implemented in a full-featured DAO object make it simple to write and read.
Active Record allows to make a number of configuration assumptions, which simplifyconfiguration files and mapping details.
Active Record Is Primarily Used for CRUD
Database Transactions. Active Record was specifically designed to make CRUD operations easy to write and understand.
-
DAO VS Active Record Pattern
References
Compare Martin Fowler's articles on ActiveRecord[1] and DataMapper[2] (his name for DAO)
Both patterns relational entitiesthat are used for data access.
The ActiveRecordpattern is characterized by a domain model that "knows" it is persistent- each entity class has a Save() method on it.
In contrast, the entire point of the DAOpattern is that the entities do not know that they are persistent objects.
CRUD
CRUD is a description of some generic operations on stored data, with no particular intention of serving as a distribution protocol, and thus little or no planning for the mitigation of problems such as accidental duplicates, time-outs or lost requests.
The following
examples display the four basic CRUD operations as you would see them in most Active Record
programs:
newacc = new Account(...);
newacc.save();
temp = Account.find(1)//Select the record associated with id of 1
temp.username = “Kevinâ€;
temp.save();
Account.destroy_all(1);
ORM
ORM stands for Object-relational mapping. It is a programming techniquefor converting data between mapping objects and database records.
In ORM relational databases records are represented in object-based codeby simply thinking of:
- database tables as classes,
- table rows as objects,
- table fields as object attributes.
ORM tools provide data access layer following the active record model. ORM/active-record modelis a popular with web frameworks.
ORM has support for most of all modern database systems, is platform independent, we canlearn just one API instead of dealing with various database
implementations.
Anything you can do with Java objects, such
as inheritance, overriding of methods also can be done with
ORM objects.
There are two separate things: Java objects and database records. As such, you sometimes have your database recordin a different stateor with a different value than
its corresponding DAOand its attributes. This is probably most obvious when
you are dealing with data validations. When a data validation fails during an attempt to save,
your DAO object attribute will still have the value assigned by your application (which
fails validation), but your database record will not have been updated
.
-
Saving new records, updating existing ones, or
-
simply accessing data
There are three general steps to follow:
-
Create a mapping object (either an Active Record or an DAO object)
-
Manipulate or access the attributes of the object.
-
Save the attributes as a record in the database.
Updating data can be done using the previous steps or with
a special update call shown in the following example:
Account.update(1, "Username = Kevin")
It’s important to remember that your changes are not reflected
within your database until you make a call to the save method.
Creating a mapping Object
with a call to the create or new method
use one of the various find
methods
(passing the primary key of the record)
Manipulating or Accessing the Attributes of mapping Objects
set or get all of its attributes of the mapping object.
DEF: transparent persistence
-
Persistence is said to be "orthogonal" or "transparent" when it is implemented as an intrinsic property of the execution environment of a program. An orthogonal persistence environment does not require any specific actions by programs running in it to retrieve or save their state. The advantage of orthogonal persistence environments is simpler and less error-prone programs.
-
Non-orthogonal persistence requires data to be written and read to and from storage using specific instructions in a program, resulting in the use of persist as a transitive verb: On completion, the program persists the data.
JDO (Java Data Object)
JDO is a specification of Java object persistence. One of its features is a transparency of the persistent services to the domain model.
JDO are ordinary POJOs which work within a Java SE environment.
(see “JDO & JPAâ€)
JPA (Java Persistence API)
JPA covers three areas:
-
the API itself, defined in the javax.persistence package
-
the Java Persistence Query Language (JPQL)
-
object/relational metadata
To compete with JDO the JPA has been "broken out" of "EJB3 Core" as new persistent standard.
JPA uses the javax.persistence package. Significantly, javax.persistencewill not require an EJB container, and thus will work within a Java SE environment as well, as JDO always has.
(see “JDO & JPAâ€)
JPA & JDO
Object persistence is defined in the external XML metafiles, which may have vendor-specific extensions. Vendors provide developers with enhancers, which modify compiled Java class files so they can be transparently persisted.
JPA, however, is an Object-relational mapping standard, while JDO is both an Object-relational mapping standard and a transparent object persistence standard.
JDO, from an API point of view, is agnostic to the technology of the underlying datastore, whereas JPA is targeted to RDBMS datastores (although there are several JPA providers that support access to non-relational datastores through the JPA API, such as EclipseLink, DataNucleus and ObjectDB).