Wednesday, July 18, 2012

Application Middleware Design

copyright from: www.dsoftworld.com
Business Logic Layer

The business logic layer is an abstract layer that contains all the rules, workflow and validation that define and deal with the business complexities that your software has been designed to meet. Typically, the business logic layer will fit between your user interface, service, or presentation layer and your data access layer. By separating the business logic from other layers in your applications you are separating your concerns and keeping your code loosely coupled and allowing for different implementations to be used with the business logic layer; for example, changing the UI from a web application to a WPF application.

WPF Win Forms --- Web Forms --- Other Services
-------------------------------------------------------------------
Service Layer
-------------------------------------------------------------------
Business Logic Layer
-------------------------------------------------------------------
Data Access Layer
-------------------------------------------------------------------
Data Sources

Depending on the complexities of the business model that your application has been designed for, the structure of your business logic layer may differ considerably. For instance a complex banking application will have a rich Domain Model that represents the real banking domain with hundreds of small business entities representing loans, customers, and accounts. For a simpler application, such as a blogging engine, you may have a number of fairly simple business objects that map very closely to your underlying Data Model with little or no business logic, simply acting as a method to add and retrieve data. In the next section, you will look at the various patterns at your disposal to structure your business logic layer.

Patterns for Your Business

There are a number of design patterns that you can follow that will help you to organize your business logic. In the below part, you will be introduced to three of the main patterns found in the business logic layer: the Transaction Script, Active Record, and the Domain Model pattern.

Transaction Script

Transaction Script is a very simple business design pattern, which follows a procedural style of development rather than an object - oriented approach. Simply create a single procedure for each of your business transactions with each procedure containing all of the business logic that is required to complete the business transaction from the workflow, business rules, and validation checks to persistence in the database.
One of the strengths of the Transaction Script pattern is that it is very simple to understand and clear to see what is going on without any prior knowledge of the pattern. If a new business case needs to be handled, it is straightforward enough to add a new method to handle it, which will contain all of the related business logic.

The problems with the Transaction Script pattern are revealed when an application grows and the business complexities increase. It is very easy to see many management or application classes with hundreds of fine - grained transaction methods that map directly to a business use cases. Sub methods can be used to avoid repetitive code such as the validation and business rules, but duplication in the workflow cannot be avoided, and the code base can quickly become unwieldy and unmanageable as the application grows.

If you have a simple application with minimal business logic, which doesn’t warrant a fully object - oriented approach, the Transaction Script pattern can be a good fit. However, if your application will grow, you may need to rethink your business logic structure and look to a more scalable pattern like the Active Record pattern.

Active Record Pattern

The Active Record pattern is very popular pattern and is especially effective when your underlying database model matches your business model. Typically, a business object will exist for each table in your database. 
The Active Record pattern is great for very simple applications where there is a one-to-one mapping between the Data Model and the Business Model, such as with a blogging or a forum engine; it ’ s also a good pattern to use if you have an existing database model or tend to build applications with a “ data first ” approach. Because the business objects have a one - to - one mapping to the tables in the database and all have the same CRUD (create, read, update, and delete) methods, it ’ s possible to use code generation tools to auto - generate your business model for you. Good code gen tools will also build in all of the database validation logic to ensure that you are allowing only valid data to be persisted. 

However, the Active Record pattern is no silver bullet. It excels with a good underlying Data Model that maps to the business model, but when there is a mismatch, sometimes called an impedance mismatch, the pattern can struggle to cope. This is the result of complex systems sometimes having a very different conceptual business models than the Data Model. When there is a rich business domain with lots of complex rules, logic, and workflow, this favors going with the Domain Model approach.

Domain Model Pattern

You can think of a Domain Model as a conceptual layer that represents the domain you are working in. Things exist in this model and have relationships to other things. What do I mean by things? Well, for example, if you were building an e - commerce store, the “things” that would live in the model would represent a Basket, Order, and Order Item, and the like. If you were creating a loan application, you would have representations for a Borrower, Loan, Assets, and Debts. It’s these things that have data and, more importantly, behavior. Not only would an order have properties that represent a creation date, status, and order number, but it would also contain the business logic to apply a voucher to, including all of the domain rules that surround it — Is the voucher valid? Can the voucher be used with the products in the basket? Are there any other offers in place that would render the voucher invalid, and so forth. The closer your Domain Model represents the real domain the better, as it will be easier for you to understand and replicate the complex business logic, rules, and validation process. 

The main difference between the Domain Model and the Active Record pattern is that the business entities that live in the Domain Model have no knowledge of how to persist themselves, and there doesn’t necessarily need to be one - to - one mapping between the Data Model and the Business Model.

As mentioned earlier, the Domain Model, unlike the Active Record pattern, has no knowledge of persistence. The term persistence ignorant (PI) has been coined for the plain nature of the POCO(plain old common runtime object) business entities. How then do you persist a business object with the Domain Model? 

Typically, the repository pattern is used. When you are employing the Domain Model pattern, it’s the responsibility of the Repository object, along with a data mapper, to map a business entity and its object graph of associated entities to the Data Model. Be aware that business entities inside the Domain Model are PI.

Trying to solve complex business problems in software is difficult, but when using the Domain Model pattern, you first create an abstract model of the real business model. With this model in place, you can then model complex logic by following the real domain and recreating the workflow and processing in your Domain Model. Another advantage that a Domain Model holds over the Transaction Script and the Active Record patterns is that, because it contains no data access code, it can be easily unit tested without having to mock and stub out dependencies of such a data access layer.

Again, the Domain Model pattern may not always be a great fit for your application needs. One of its great strengths is dealing with complex business logic, but a full - blown Domain Model is architectural overkill when very little business logic is contained within the application. Another disadvantage of the pattern is the steep learning curve needed to become proficient in it compared to the Active Record and Transaction Script options. To use the pattern effectively takes time and experience and, most importantly, a sound knowledge of the business domain you are trying to model.

Which Pattern to Use?

Each pattern has its pros and cons, and there is no one method that will suit all of your development needs. Let’s take a brief look at each pattern and see when it’s most appropriate to use it. 

Transaction Script: If you have a simple application with little or no logic, then Transaction Script is a great choice as a straightforward solution that is easily understood by other developers picking up your code down the line.

Active Record: If your business layer is simply a thin veil over the top of your database, then this is a great pattern to opt for. There are many code generation tools that can automatically create your business objects for you based on your database schema, and it ’ s not too difficult to create your own.

Domain Model: The Domain Model excels when you have an involved, rich complex business domain to model. It’s a pure object - oriented approach that involves creating an abstract model of the real business domain and is very useful when dealing with complex logic and workflow.
The Domain Model is persistence ignorant and relies on mapper classes and the Repository pattern to persist and retrieve business entities.

It now your decision how to implement your application’s Middleware. But keep in mind that a good design will calculate the support time and application extensibility.

Stay tuned for more, and share it with your Development cycle.

Design Patterns Applicability

copyright from: www.dsoftworld.com


Creational Patterns

Abstract factory (Kit)

Use the Abstract Factory pattern when

o A system should be independent of how its products are created, composed, and represented.

o A system should be configured with one of multiple families of products.

o A family of related product objects is designed to be used together, and you need to enforce this constraint.

o You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

Builder

Use the Builder pattern when

o The algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled.

o The construction process must allow different representations for the object that's constructed.

Factory Method (virtual constructor)

Use the Factory Method pattern when

o A class can't anticipate the class of objects it must create.
o A class wants its subclasses to specify the objects it creates.
o Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.


Prototype

Use the Prototype pattern when

o a system should be independent of how its products are created, composed, and represented; 

and

o when the classes to instantiate are specified at run-time, for example, by dynamic loading; 

or

o to avoid building a class hierarchy of factories that parallels the class hierarchy of products; or

o When instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state.

Singleton

Use the Singleton pattern when

o There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
o When the sole instance should be extensible by sub classing, and clients should be able to use an extended instance without modifying their code.


Structural Patterns

Adapter (Wrapper)

Use the Adapter pattern when

o You want to use an existing class, and its interface does not match the one you need.

o You want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces.

o (Object adapter only) you need to use several existing subclasses, but it's impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.


Bridge (Handle/Body)

Use the Bridge pattern when

o You want to avoid a permanent binding between an abstraction and its implementation. This might be the case, for example, when the implementation must be selected or switched at run-time.

o Both the abstractions and their implementations should be extensible by subclassing. In this case, the Bridge pattern lets you combine the different abstractions and implementations and extend them independently.

o Changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled.

o (C++) you want to hide the implementation of an abstraction completely from clients. In C++ the representation of a class is visible in the class interface.

o You have a proliferation of classes as shown earlier in the first Motivation diagram. Such a class hierarchy indicates the need for splitting an object into two parts. Rumbaugh uses the term "nested generalizations"

o To refer to such class hierarchies.

o You want to share an implementation among multiple objects (perhaps using reference counting), and this fact should be hidden from the client.


Composite

Use the Composite pattern when

o you want to represent part-whole hierarchies of objects.

o you want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly.

Decorator (Wrapper)

Use Decorator

o To add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.

o For responsibilities that can be withdrawn.

o When extension by subclassing is impractical. Sometimes a large number of independent extensions are

o Possible and would produce an explosion of subclasses to support every combination. Or a class definition

o May be hidden or otherwise unavailable for subclassing.

Façade

Use the Facade pattern when

o You want to provide a simple interface to a complex subsystem. Subsystems often get more complex as they

o Evolve. Most patterns, when applied, result in more and smaller classes. This makes the subsystem more

o Reusable and easier to customize, but it also becomes harder to use for clients that don't need to customize it. A

o Facade can provide a simple default view of the subsystem that is good enough for most clients. Only clients

o Needing more customizability will need to look beyond the facade.

o There are many dependencies between clients and the implementation classes of an abstraction. Introduce a

o facade to decouple the subsystem from clients and other subsystems, thereby promoting subsystem independence and portability.

o You want to layer your subsystems. Use a facade to define an entry point to each subsystem level. If subsystems are dependent, then you can simplify the dependencies between them by making them Communicate with each other solely through their facades.

FlyWeight

The Flyweight pattern's effectiveness depends heavily on how and where it's used. Apply the Flyweight pattern when all of the following are true:

o An application uses a large number of objects.

o Storage costs are high because of the sheer quantity of objects.

o Most object state can be made extrinsic.

o Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed.

o The application doesn't depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects.

Proxy (Surrogate)

Proxy is applicable whenever there is a need for a more versatile or sophisticated reference to an object than a simple pointer. Here are several common situations in which the Proxy pattern is applicable:

o A remote proxy provides a local representative for an object in a different address space. Coplien calls this kind of proxy an "Ambassador."

o A virtual proxy creates expensive objects on demand.

o A protection proxy controls access to the original object. Protection proxies are useful when objects should have different access rights. For example, KernelProxies in the Choices operating system provide protected access to operating system objects.

o A smart reference is a replacement for a bare pointer that performs additional actions when an object is accessed. Typical uses include counting the number of references to the real object so that it can be freed automatically when there are no more references (also called smart pointers).

o Loading a persistent object into memory when it's first referenced.

o Checking that the real object is locked before it's accessed to ensure that no other object can change it.


Behavioral Patterns

Chain of responsibility

Use Chain of Responsibility when

o More than one object may handle a request, and the handler isn't known a priori. The handler should be ascertained automatically.

o You want to issue a request to one of several objects without specifying the receiver explicitly the set of objects that can handle a request should be specified dynamically.

Command (Action, Transaction)
Use the Command pattern when

o You want to parameterize objects by an action to perform, as MenuItem objects did above. You can express such parameterization in a procedural language with a callback function, that is, a function that's registered somewhere to be called at a later point. Commands are an object-oriented replacement for callbacks.

o Specify, queue, and execute requests at different times. A Command object can have a lifetime independent of the original request. If the receiver of a request can be represented in an address spaceindependent way, then you can transfer a command object for the request to a different process and fulfill the request there.

o Support undo. The Command's Execute operation can store state for reversing its effects in the command itself. The Command interface must have an added Unexecute operation that reverses the effects of a previous call to Execute. Executed commands are stored in a history list. Unlimited-level undo and redo is achieved by traversing this list backwards and forwards calling Unexecute and Execute, respectively.

o Support logging changes so that they can be reapplied in case of a system crash. By augmenting the Command interface with load and store operations, you can keep a persistent log of changes.

o Recovering from a crash involves reloading logged commands from disk and reexecuting them with the Execute operation.

o Structure a system around high-level operations built on primitives operations. Such a structure is common in information systems that support transactions. A transaction encapsulates a set of changes to data. The Command pattern offers a way to model transactions. Commands have a common interface, letting you invoke all transactions the same way. The pattern also makes it easy to extend the system with new transactions.

Interpreter

Use the Interpreter pattern when there is a language to interpret, and you can represent statements in the language as abstract syntax trees. The Interpreter pattern works best when

o The grammar is simple. For complex grammars, the class hierarchy for the grammar becomes large and unmanageable. Tools such as parser generators are a better alternative in such cases.

o They can interpret expressions without building abstract syntax trees, which can save space and possibly time.

o Efficiency is not a critical concern. The most efficient interpreters are usually not implemented by interpreting parse trees directly but by first translating them into another form. For example, regular expressions are often transformed into state machines. But even then, the translator can be implemented by the Interpreter pattern, so the pattern is still applicable.

Iterator (Cursor)

Use the Iterator pattern

o To access an aggregate object's contents without exposing its internal representation.

o To support multiple traversals of aggregate objects.

o To provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration).

Mediator

Use the Mediator pattern when

o a set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand.

o reusing an object is difficult because it refers to and communicates with many other objects.

o a behavior that's distributed between several classes should be customizable without a lot of subclassing.

Memento (Token)

Use the Memento pattern when

o A snapshot of (some portion of) an object's state must be saved so that it can be restored to that state later, and

o A direct interface to obtaining the state would expose implementation details and break the object's encapsulation.

Observer (Dependents, Publish-Subscribe)

Use the Observer pattern in any of the following situations:

o When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.

o When a change to one object requires changing others, and you don't know how many objects need to be changed.

o When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled.

State (Objects for States)

Use the State pattern in either of the following cases:

o An object's behavior depends on its state, and it must change its behavior at run-time depending on that state.

o Operations have large, multipart conditional statements that depend on the object's state. This state is usually represented by one or more enumerated constants. Often, several operations will contain this same conditional structure. The State pattern puts each branch of the conditional in a separate class. This lets you treat the object's state as an object in its own right that can vary independently from other objects.

Strategy (Policy)

Use the Strategy pattern when

o Many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many behaviors.

o You need different variants of an algorithm. For example, you might define algorithms reflecting different space/time trade-offs. Strategies can be used when these variants are implemented as a class hierarchy of algorithms

o An algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures.

o A class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class.

Template Method

The Template Method pattern should be used

o To implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary.

o When common behavior among subclasses should be factored and localized in a common class to avoid code duplication. This is a good example of "refactoring to generalize" as described by Opdyke and Johnson. You first identify the differences in the existing code and then separate the differences into new operations. Finally, you replace the differing code with a template method that calls one of these new operations.

o To control subclasses extensions. You can define a template method that calls "hook" operations at specific points, thereby permitting extensions only at those points

Visitor

Use the Visitor pattern when

o An object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes.

o Many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes with these operations. Visitor lets you keep related operations together by defining them in one class. When the object structure is shared by many applications, use Visitor to put operations in just those applications that need them.

o The classes defining the object structure rarely change, but you often want to define new operations over the structure. Changing the object structure classes requires redefining the interface to all visitors, which is potentially costly. If the object structure classes change often, then it's probably better to define the operations in those classes.

reference:
Design Patterns: Elements of Reusable Object-Oriented Software book