COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor...

40
COMP610E Software Development of E-Business Applications A Report: Software Architecture AntiPatterns Ip Kin Sang [email protected] Abstract The study of AntiPatterns has recently emerged as a research area for detecting problematic constructions in OO designs. An AntiPattern describes a solution to a recurrent problem that generates negative consequences to the software. This report first introduces AntiPatterns and then the discussion will focus on four Software Architecture AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns and their solutions will be discussed in details. Lastly, the applications of the strategies in solutions to these AntiPatterns in other aspects such as J2EE Design Patterns are also discussed.

Transcript of COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor...

Page 1: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

COMP610E Software Development of E-Business Applications

A Report: Software Architecture AntiPatterns Ip Kin Sang

[email protected]

Abstract The study of AntiPatterns has recently emerged as a research area for detecting problematic constructions in OO designs. An AntiPattern describes a solution to a recurrent problem that generates negative consequences to the software. This report first introduces AntiPatterns and then the discussion will focus on four Software Architecture AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns and their solutions will be discussed in details. Lastly, the applications of the strategies in solutions to these AntiPatterns in other aspects such as J2EE Design Patterns are also discussed.

Page 2: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Table of Contents Abstract ..............................................................................................................................1 1. Introduction ......................................................................................................................4 2. Stovepipe System.............................................................................................................8

2.1 AntiPattern Name: Stovepipe System.......................................................................8 2.2 General Form .............................................................................................................8 2.3 Symptoms and consequences.....................................................................................8 2.4 Typical Causes of the Problem..................................................................................9 2.5 Refactored Solution....................................................................................................9 2.6 Example ...................................................................................................................11

3. Vendor Lock-In..............................................................................................................16 3.1 AntiPattern Name: Vendor Lock-In.........................................................................16 3.2 General Form ...........................................................................................................16 3.3 Symptoms and Consequences ..................................................................................16 3.4 Typical Causes of the Problem................................................................................16 3.5 Refactored Solution..................................................................................................17 3.6 Example ...................................................................................................................19

4. Circuitous Treasure Hunt...............................................................................................21 4.1 AntiPattern Name: Circuitous Treasure Hunt .........................................................21 4.2 General Form ...........................................................................................................21 4.3 Symptoms and consequences...................................................................................21 4.4 Typical Causes of the Problem................................................................................22 4.5 Refactored Solution..................................................................................................22 4.6 Example ...................................................................................................................23

5. Excessive Dynamic Allocation......................................................................................32 5.1 AntiPattern Name: Excessive Dynamic Allocation ................................................32 5.2 General Form ...........................................................................................................32 5.3 Symptoms and consequences...................................................................................32 5.4 Typical Causes of the Problem................................................................................32 5.5 Refactored Solution..................................................................................................33 5.6 Example ...................................................................................................................34

6. Conclusion .....................................................................................................................39 7. References......................................................................................................................40

Page 3: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Table of Figures Figure 1 Design Pattern and AntiPattern concepts ..............................................................4 Figure 2 Stovepipe interfaces require point-to-point integration, ........................................8 Figure 3 Component architectures model interoperability needs with common interfaces.9 Figure 4 Client/server Stovepipe System...........................................................................11 Figure 5 The refactored architecture abstracts subsystem differences. .............................12 Figure 6 Sequence diagram for the Session Façade to access ...........................................14 Figure 7 Service Activator hides the complexity of service lookup. .................................15 Figure 8 The isolation layer separates application software from .....................................17 Figure 9 The DAO acts as an adapter between the business object and the data source. ..20 Figure 10 ICAD Classes and Associations. .......................................................................23 Figure 11 DrawMod Example of Circuitous Treasure Hunt. ............................................24 Figure 12 Refactored DrawMod Scenario. ........................................................................25 Figure 13 Value Object Assembler sequence diagram. .....................................................27 Figure 14 Merging Session Beans. ....................................................................................28 Figure 15 Fast Lane Reader. ..............................................................................................30 Figure 16 Excessive Dynamic Allocation. .........................................................................34 Figure 17 Life Cycle of an Entity Bean Instance. ..............................................................35 Figure 18 Connection management using JDBC 1.0. ........................................................36 Figure 19 Connection pooling using JDBC 2.0 Standard extension. ................................37 Figure 20 Logical view of prepared statements reused by pooled connections. ...............37 Figure 21 Structure of Helper Class...................................................................................38

Page 4: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

1. Introduction As the field of software engineering matures, the focus of study is shifting towards decreasing effort and increasing efficiency of software production. Much emphasis has been put on software reuse. Software reuse initially meant developing code in such a way as to make it available for multiple clients. Although code reuse is still important, focus is now shifting to higher-level entities in software development such as design and processes. The software architect, Christopher Alexander developed the idea of using basic architecture patterns as fundamental building blocks. The design patterns, time-tested and shown to work in specific situations, could then be used and applied where most appropriate. The design patterns have gained widely spread public interest since 1994. Introduction to Design Pattern A design pattern focuses on a particular software design problem or issue. It contains a detailed discussion of how this problem can be apportioned into a context. This describes the circumstances under which the problem is applicable, and the individual motivating factors, or the forces that need to be resolved. The design pattern then describes how these forces are either resolved or balanced within the scope of that context to provide a solution. The solution then diverges into benefits, related solutions and remaining negative forces called consequences.

Figure 1 Design Pattern and AntiPattern concepts Introduction to AntiPattern In reality, only a few pre-existing concerns can affect the system design in the specific context that the Design Patterns generally assume. It has been demonstrated that situations with legacy and existing problems are much more commonplace in practice. The AntiPatterns start with an existing "negative solution" or legacy approach. This

Page 5: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

“negative solution” may be the result of a manager or developer’s ignorance or inexperience in solving a particular type of problems, or perhaps having applied a perfectly good design pattern in a wrong context. The AntiPattern then amplifies the negative solution in a way that helps organizations recognize and understand a problematic situation, its symptoms, and its ultimate consequences. The AntiPattern can present a common solution that refactors the system to maximize benefits and minimize adverse consequences. AntiPattern leads to refactored solution AntiPatterns are based on a structure that differs from simple Design Patterns. AntiPatterns begin with a compelling, problematic solution. From this solution, a discussion of the root causes records how the problematic solution is the result of incorrectly resolving the forces for a specific underlying set of problems within its context. This convergence from a concrete problematic situation to the more abstract underlying forces is an important step in order to understand how and why the problem exists. This abstraction is composed of symptoms and consequences, which clearly documents the implications of the problematic solution. The documented symptoms can then be critical information used in the diagnosis and recognition of a specific problematic solution, or, AntiPattern. Finally, once an AntiPattern has been correctly identified, its refactored solution can be used to obtain a better convergence of the underlying forces to lead you to a better understanding of the problem and an effective method of resolving the problematic solution. AntiPatterns provide real-world experience in recognizing recurring problems in the software industry The AntiPatterns focus on the wide and ever-growing collection of repeated software failures in an attempt to understand, prevent and recover from them. To the developer, AntiPatterns are new tools that bridge the gap between architectural concepts and real-world implementations. AntiPatterns highlight the most common problems that face the software industry and provide the tools to enable you to recognize these problems and to determine their underlying causes. The AntiPatterns are also used to illustrate the important common, critical problems faced by most software developers and share the wisdom learnable from other developers’ experiences. Only with an understanding of the causes and motivations of an AntiPattern can developers ensure that such negative solutions are not continually repeated within an organization.

Page 6: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

AntiPatterns provide a detailed remedy for the most common unpleasant situation AntiPatterns are also a method for efficiently mapping a general problematic situation to a specific class of solutions. AntiPatterns present a detailed plan for reversing the underlying causes for the identified problems and implementing productive solutions. AntiPatterns also effectively describe the measures that can be taken at several levels to improve the development of applications, the designing of software systems, and the effective management of software projects. Three main categories of AntiPatterns The AntiPatterns can be classified into three main categories [Brown et al. 1998].

1. Software Development AntiPatterns . These AntiPatterns are under the concern of the software developers. It describes situations encountered by the programmers when solving programming problems.

2. Software Architecture AntiPatterns. These AntiPatterns are under the concern

of the software architects. It focuses on common problems in system structure, their consequences, and solutions.

3. Software Management AntiPatterns. These AntiPatterns are under the concern

of the software managers. It describes common problems and solutions due to the software organization and project management.

Focus of this Report This report focuses on the Software Architecture AntiPatterns because: 1. Many of the most serious unresolved problems in software systems occur from

the perspective of software architecture.

2. Good architecture is a critical factor in the success of the system development.

3. Software Development AntiPatterns focus on the programming problems rather than the software design problems.

4. Software Management AntiPatterns are not concerned with the technical software

design, but rather about the management of software process, resources and external customer relationships.

Among the software architecture AntiPatterns, we discuss those AntiPatterns that are related to the functional partitioning of software modules, the software interfaces among modules and the software architecture dependent performance. They are Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation.

Page 7: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

AntiPattern Templates Before discussing the AntiPatterns, the documentation methods of the AntiPatterns are first described. There are two main templates for documenting AntiPatterns, the Mini-AntiPattern and the Full-AntiPattern Templates. The full AntiPattern template is composed of a number of required and optional sections but mos t of the sections are too detailed to be included in this report. Instead, the Mini-AntiPattern template with the extension of some template sections is chosen so as to provide a concise AntiPattern description. The core sections are the AntiPattern Name, General Form, Symptoms and Consequences, Refactored Solution and Example. AntiPattern Name

The name of the AntiPattern.

General Form A generic description to identify the general characteristics of the AntiPattern.

Symptoms and Consequences

A list of problematic symptoms and consequences that result from the AntiPattern.

Refactored Solution

A refactored solution to the AntiPattern described in the General Form section.

Example The example demonstrates how the solution is applied to a problem suffering from the AntiPattern. The strategies applied in the refactored solution to the AntiPatterns are also applied in other aspects, such as J2EE design patterns published by different organizations, Enterprise JavaBeans and JDBC API. This section will be extended with description of applying the strategies so as to encourage the readers to apply the strategies in software design.

Page 8: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

2. Stovepipe System

2.1 AntiPattern Name: Stovepipe System

2.2 General Form The Stovepipe System AntiPattern involves a lack of coordination and planning across a set of systems. The Stovepipe System AntiPattern addresses how the subsystems are coordinated within a single large system. The main problem in this AntiPattern is the lack of common subsystem abstractions . The subsystems are integrated in an ad hoc manner using multiple integration strategies and mechanisms. All subsystems are integrated point to point, as shown in Figure 2 below, so the integration approach for each pair of subsystems cannot be easily reused for the integration of other subsystems. Furthermore, the system implementation is unstable because there are many implicit dependencies upon system configuration, installation details, and system state. The system is difficult to extend, and extensions add additional point -to-point integration links. As each new capability and system alteration is integrated, system complexity increases, throughout the life cycle of the stovepipe system. Subsequently, system extension and maintenance become increasingly difficult to manage.

Figure 2 Stovepipe interfaces require point-to-point integration, which leads to order (N X N) system cost and complexity.

2.3 Symptoms and consequences 1. Changes to the systems become increasingly difficult. Requirements changes are

costly to implement, and system modifications become increasingly likely to introduce new serious bugs. Moreover, system maintenance generates surprising costs. Project is over -budget and has slipped its schedule for no obvious reason.

2. Interoperability with other systems cannot be easily achieved, and there is an

inability to support integrated system management and intersystem security capabilities. Architects are unfamiliar with key aspects of integration solutions, and they must invent workarounds to cope with limitations of the system.

Page 9: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

3. A large semantic gap exists between architecture documentation and implemented software. The documentation does not correspond to the system implementation. The system may comply with most paper requirements but it does not meet user expectations.

2.4 Typical Causes of the Problem 1. Multiple infrastructure mechanisms are used to integrate subsystems. Therefore,

the absence of a common mechanism makes the architecture difficult to describe and modify. This absence is because of the lack of architectural vision of integration while developing the subsystems.

2. In some cases, there is no abstraction of the services provided by a subsystem. In

other cases, all provided interfaces are unique to each subsystem and this makes it difficult for the subsystem integration.

3. The metadata of the databases are insufficiently used in the system development. In

particular, the metadata is not available to support system extensions and reconfigurations so as to minimize the changes in software.

4. The tight coupling among implemented classes requires excessive client code that is

specific for utilizing services provided by other classes.

2.5 Refactored Solution System abstractions model interoperability needs The refactored solution to the Stovepipe System AntiPattern is a component architecture that provides a flexible substitution of software modules. Subsystems are modeled abstractly so that there are many fewer exposed interfaces than there are subsystem implementations. The module substitution can be both static compile-time replacement of components and dynamic binding of components at run-time. The key to defining the component interfaces is to discover the appropriate abstractions. The subsystem abstractions model the interoperability needs of the system without exposing unnecessary differences between subsystems and implementation-specific details, as shown in the Figure 3 below.

Figure 3 Component architectures model interoperability needs with common interfaces.

Page 10: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Provide abstraction of subsystem services In order to define the component architecture of the system, we should choose a base level of functionality that the majority of applications will support. In general, that level should be low and focus upon a single aspect of interoperability, such as data interchange or conversion among subsystems. Then, we define a set of system interfaces that support this base level of functionality. Most services have an additional interface to express finer-grained functional needs, so each component interface defined should be small. Thin clients Having a base level of component services available to all clients in the domain encourages the development of thin clients that work well with existing and future services, without any modification. Thin clients do not require detailed knowledge of the services and architecture of the system as the system framework may support and simplify their access to complex services. Having several plug-compatible implementations available increases the robustness of clients, as they potentially have many options in fulfilling their service request. Provide specialized vertical interfaces Applications will have clients that are written to more specialized or vertical interfaces. Vertical clients should remain unaffected by the addition of the new component interfaces. Clients that require only the base level of functionality can be written to the horizontal interfaces, which should be more stable and easily supported by new or othe r existing applications. The horizontal interface should hide, via abstraction, all the lower level details of a component and provide only the base-level functionality. The client should be written to handle whatever data types as indicated in the interface in order to support any future change of the horizontal component implementations. For example, if a user-defined type is returned, the client should be capable of handling all types of data that the user-defined type may contain. Metadata decouple clients from services Incorporation of metadata into the component architecture is important to service discovery and service discrimination. A fundamental level of metadata support is through naming and trading services. Naming services enables the discove ry of known objects whereas a trading service lists the available services and their properties for discovery by clients. Interoperable naming services are extended to incorporate some trading capabilities. More extensive use of metadata is usually required for enhancing the decoupling of clients from services they use. For example, schema metadata for database services helps clients to adapt to alternative schema and schema changes in database services.

Page 11: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

2.6 Example The Figure 4 below is a representation of a typical client/server stovepipe system [Brown et al. 1998]. There are three client subsystems and six service subsystems. Each service subsystem has a unique software interface, and each service subsystem instance is modeled as a class in the class diagram. When the system is constructed, each client provides unique interface software for each of the integrated service subsystems. If additional service subsystems are added or substituted for existing ones, the clients must be modified with additional code that integrates the newly added unique interfaces. Therefore, the tight coupling between clients and subsystems pays significant costs on system updates and maintenance.

Figure 4 Client/server Stovepipe System.

Page 12: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Refactored solution to Example The refactored solution to this bad design considers the common abstractions among the subsystems. Since there are at least two services of each subsystem service type, it is possible for each subsystem model to have one or more service interface in common. Then each particular device or service can be wrapped to support the common interface abstraction. If additional devices are added to the system from the abstract subsystem categories, they can be integrated transparently to the existing system software. The addition of a trader service adds the ability to discover and discriminate among the abstracted services provided by the devices.

Figure 5 The refactored architecture abstracts subsystem differences.

Page 13: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Session Façade Design Pattern The design strategies in the solution to the Stovepipe System AntiPattern have also been applied in the Session Façade Design Pattern included in the Sun Java Center J2EE Patterns Release 1.0. A similar design pattern also appears in the J2EE design patterns published by the J2EE BluePrints team. The following are the problems in a multi-tiered application that the Session Façade Design Pattern tries to solve:

1. The lack of a uniform client access strategy exposes business objects to clients and this leads to the tight coupling between clients and business objects. As a result, the client implementation is directly dependent on the business tier.

2. Too many method invocations between the client and server lead to network performance problems.

The following are the motivations or forces of the Session Façade Design Pattern [Alur et al. 2001]. 1. The underlying interactions and inter-dependencies among business

components should be hidden from the client. This provides better manageability, centralization of interactions, greater flexibility, and greater ability to cope with changes.

2. A simpler interface should be provided to the clients by hiding all the complex

interactions among business components. 3. The number of business objects that are exposed to the clients across the service

layer over the network should be reduced. The underlying business objects should not be exposed directly to the clients so as to keep the coupling between the two tiers to a minimum.

4. A uniform coarse-grained service layer should be provided to separate business

object implementation from business service abstraction. Session Façade provides abstraction of business object interactions The Session Facade is a boundary object that controls the interactions between the client and the participant business data and service objects. The Session Façade abstracts the underlying business object interactions and provides a service layer that exposes only the required interfaces. Thus, it hides the client’s view from the complex interactions among the participants. The Session Façade manages the interactions between the business data and service objects that participate in the workflow, and it encapsulates the business logic associated with the requirements. Thus, the session bean, which represents the Session Façade, manages the relationships among business objects.

Page 14: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Identifying Session Facades We can identify where a Session Façade might be useful in software architecture design by studying the client requirements and interactions typically documented in use cases and scenarios. Mapping every use case to a Session Façade will result in too many Session Façades. This defeats the intention of having fewer session beans that are coarse grained. Instead, as the Session Facades are derived during the modeling, we should try to consolidate them into fewer session beans based on some logical partitioning. Example For example, for a banking application, you may group the interactions related to managing an account into a single façade. The use cases Create New Account, Change Account Information, View Account information, and so on all deal with the coarse-grained entity object Account. The functions required to support these related use cases could be grouped into a single Session Façade called AccountSessionFacade. In this case, the Session Façade will become a highly coarse-grained controller with high level methods that can facilitate each interaction. The example methods are createNewAccount(), changeAccount(), getAccount(). Aggregating a group of the related interactions into a single Session Façade results in fewer Session Facades for the application, and takes advantage of the benefits of the Session Façade pattern. Figure 6 below shows a typical sequence diagram for the interactions between the Session Façade and other objects.

Figure 6 Sequence diagram for the Session Façade to access

Entity and Session Beans, and Data Access Objects.

Page 15: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Service Locator object plays the role of Trader The session bean, which typically represents a Session Façade, manages the lifecycle of the participating business objects by creating, locating, modifying, and deleting them as required by the workflow. In a complex application, the Session Façade may delegate this lifecycle management to a separate object, such as a Service Locator object. This Service Locator plays the role of the trader in the refactored solution above. Indeed, the Service Locator is another J2EE Design Pattern proposed by Sun Java Center. The following are some of the motivations or forces of this design pattern which are related to the service lookup purpose:

1. EJB clients need to use the JNDI API to lookup EJBHome objects by using the enterprise bean's registered JNDI name.

2. Lookup and creation of service components could be complex and may be used repeatedly in multiple clients in the application.

3. Initial context creation and service object lookups, if frequently required, can be resource intensive and may impact application performance. This is especially true if the clients and the services are located in different tiers.

A Service Locator object is used in the design pattern to abstract all JNDI usage and to hide the complexities of initial context creation, EJB home object lookup, and EJB object re-creation [Alur et al. 2001]. This is shown in the sequence diagram below. Multiple clients can reuse the Service Locator object to reduce code complexity, provide a single point of control, and improve the performance by providing a caching facility.

Figure 7 Service Activator hides the complexity of service lookup.

Page 16: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

3. Vendor Lock-In

3.1 AntiPattern Name: Vendor Lock-In

3.2 General Form A software project adopts a product technology and the software becomes completely dependent upon the product vendor’s implementation. When upgrades of the product occur, software changes and interoperability problems occur. Continuous maintenance of the software, based upon product upgrades, is required to keep the system running. Expected new product features are often delayed and this causes schedule slips and inability to complete desired application software features.

3.3 Symptoms and Consequences 1. Commercial product upgrades drive the application software maintenance

cycle. Unnecessary maintenance due to product upgrades occurs to the system. 2. The promised product features are delayed or never delivered and this causes

missed feature deliveries of the application software.

3. The product varies significantly from the advertised open systems standard. This will increase the technology migration costs of the software across multiple platforms.

4. If a product upgrade is missed entirely, then a product repurchase and re-

integration of the new product is often necessary. This will increase the software maintenance costs.

3.4 Typical Causes of the Problem 1. There is no technical approach for isolating the application software from

direct dependency upon the product. The development of the application requires in-depth product knowledge and this implies that the maintenance of the software also requires in-depth product knowledge.

2. The product varies from published open system standards. The openness and

conformance to standards that the product claims have no enforceable meaning. There is no effective conformance process for the standard and this results in the strong dependence of the application software on the product.

3. The product is selected based entirely upon marketing and sales information.

There is no detailed technical inspection in the open system standards of the product.

4. The complexity and generality of the product technology greatly exceeds that of

the application needs. The direct dependence upon the product results in the

Page 17: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

difficulty for the management of complexity of the application system architecture.

3.5 Refactored Solution An Isolation Layer is a solution to the Vendor Lock-In AntiPattern. It provides a separation between application software and underlying technology of the vendor products. It can be used to provide software portability from underlying platform-specific software interfaces. The Isolation Layer solution can be applied when any of the following conditions holds:

1. The isolation of the application software from the lower-level infrastructure is needed. This lower-level infrastructure may include middleware, operating systems and security mechanisms.

2. Changes to the underlying infrastructure are anticipated within the life cycle of

the affected software. Such changes include new product releases or planned migration to a new infrastructure or platform.

3. The level of abstraction in the interfaces provided by the low-level vendor

software is too primitive or flexible for the intended applications and systems. An alternative more convenient programming interface is necessary.

4. It is desirable to provide consistency in the application software to handle the

infrastructure interface across platforms. To achieve this, some conventions for default handling of infrastructure interfaces must be provided.

5. Multiple infrastructures must be supported, either during the life cycle or

concurrently. The Isolation Layer solution facilitates the development and maintenance of software applications supporting multiple infrastructures.

Figure 8 The isolation layer separates application software from

vendor product dependent interfaces, which may change.

Page 18: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Details of the Isolation Layer The solution involves creating a layer of software that abstracts the underlying infrastructure or product-dependent software interfaces. This layer provides an application interface, which completely isolates the application software from the underlying vendor software interfaces. The application interface should provide a convenient language-specific interface to desired capabilities of the application software. The layering software should provide default handling of some infrastructure calls and parameters, but exposes other deta ils when appropriate. The isolation layer is utilized across multiple system development projects so as to assure interoperability, consistency, and isolation. When an infrastructure is updated, the isolation layer can be implemented and migrated to the updated infrastructure. The isolation layer should also be updated when the infrastructure is updated again. As a result, the same application software interface is maintained, no matter how the underlying infrastructure changes. The benefits of the refac tored solution include:

1. The risks and costs of infrastructure migration can be reduced. The risks and costs of software upgrades due to infrastructure changes can also be reduced.

2. As the risks of infrastructure migration are reduced, the system migration can be

performed more easily and so the software failure due to infrastructure changes is more likely to be avoided.

3. The transparent concurrent use of multiple infrastructures is supported. The

coordinated default handling of flexible interfaces and parameters is enforced.

4. A less labor intensive, inexpensive and convenient programming interface can be provided to most application programmers. The knowledge of the underlying infrastructure is separated from the software application knowledge. This allows a small team of infrastructure developers to maintain the isolation layer, while the majority of programmers have a customized interface to the layering software. This will facilitate the development of application software and ensure the stability of the isolation layer on updates of the underlying product.

Page 19: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

3.6 Example

The ORBlite framework provides the isolation of application software from multiple language mappings and network protocols. ORBlite is based upon HP ORBplus. ORBlite was able to support multiple language mappings for C++ when the adoption and revision process is given the evolution of the OMG mappings.

The design strategies in the solution above to the Vendor Lockin AntiPattern have also been applied in the Data Access Object Design Pattern proposed by the Sun Java Center. A similar design pattern also appears in the J2EE design patterns catalogued by the J2EE BluePrints team.

The following summarizes the problems that the Data Access Object Design Pattern intends to solve and the motivations of the design pattern.

1. Many real world J2EE applications need to use persistent data. They contain components such as bean-managed entity beans, session beans and servlets or JSP, which need to retrieve and store information from persistent stores and other data sources like legacy systems, B2B, LDAP, and so forth.

2. Applications can use the JDBC API to access data residing in a RDBMS. The

JDBC API enables standard access and manipulation of data in a persistent storage, such as a relational database. However, the access mechanisms, supported APIs, and features vary drastically when comparing a relational type of persistent storage such as RDBMS to other types of persistent stores, such as Object Oriented Databases (OODBMS) or simply flat files.

3. Persistent storage APIs also vary depending on the product vendor. Some

data sources may have APIs that are non-standard and do not conform to open standards. These APIs and their capabilities also vary depending on the storage type. There is a lack of uniform APIs to address the requirements to access the greatly different persistent storage systems.

4. Components accessing legacy systems to retrieve and store data is typically done

using proprietary APIs. When business components need to access a data source, they can use the appropriate API to achieve connectivity and manipulate the data source.

However, including the connectivity and data access code within these components introduces a tight coupling between the components and the data source access implementation. Such code dependencies in the components makes it difficult and tedious to migrate the application from one type of data source to another. When the data source changes, the components need to be changed to handle the new type of data source.

Page 20: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

5. Portability of the components is directly affected when specific access

mechanisms and APIs are included in the components. Components need to be transparent to the actual persistent store or data source access implementation to provide easy migration to different vendor products, different storage types, and different data source types.

Data Access Object Design Pattern Details The DAO Design Pattern uses a Data Access Object (DAO) to abstract and encapsulate all access to the data source. The DAO is the core object of this pattern [Alur et al. 2001] . The DAO manages the connection with the data source to retrieve and store data. The DAO also implements the access mechanism required to work with the data source. The data source could be a persistent store such as a RDBMS, an external B2B exchange service or a LDAP database repository. The business component that relies on the DAO object uses the simpler interface exposed by the DAO for its clients. The DAO completely hides the data source implementation details from its clients. As the interface exposed by the DAO to clients does not change when the underlying data source implementation changes, this pattern allows the DAO to adapt to different storage schemes without affecting its clients or business components. Essentially, the DAO acts as an adapter between the component and the data source. Figure 9 below shows a typical sequence diagram for the interactions among a business object, the DAO and the data source.

Figure 9 The DAO acts as an adapter between the business object and the data source.

Page 21: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

4. Circuitous Treasure Hunt

4.1 AntiPattern Name: Circuitous Treasure Hunt

4.2 General Form The Circuitous Treasure Hunt AntiPattern is typically found in database applications. Software system retrieves data from the first table in a database, uses those results to search the second table, retrieves data from that table, and so on, until the “ultimate results” are obtained. A large amount of database processing is required for each time the “ultimate results” is retrieved. This will result in performance degradation for the application because of the high volume of database accesses. Another instance of this AntiPattern is also found in object -oriented systems, where operations have large “response sets.” In this case, one object invokes an operation in another object, that object then invokes an operation in another object, and so on, until the “ultimate result” is obtained. Then, each operation returns, one by one, to the object that made the original call. The performance of the systems will deteriorate due to such chaining of the method invocations among different objects.

4.3 Symptoms and consequences 1. In order to obtain the “ultimate results”, the database needs to process a large

amount of queries. This burden on the database leads to performance degradation of the database in processing other query requests.

2. The large amount of database processing is especially problematic when the

database is on a remote server as this causes the network performance degradation in addition to the processing burden of the database.

3. The chaining of the method invocations at different objects requires an extra

processing to identify the final operation to be called and invoked, especially in distributed object systems where objects involved may reside in other processes and on other processors.

4. When the method invocation causes the intermediate objects to be created and

destroyed, the impact on performance degradation is even greater. The memory allocation and de-allocation of the intermediate objects are frequently performed and they also consume system resources.

Page 22: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

4.4 Typical Causes of the Problem 1. When the database is on a remote server, each database access requires

transmitting all the intermediate queries and results via a network, and the access may route through middleware and other servers in a multi-tier environment. This results in network performance degradation for the application because of the large amount of interaction across the network layer.

2. The same reason applies because the intermediate objects are created and route

through the network layer when the return value of a method serves as the parameter of the method invocation at another object.

3. This AntiPattern also has poor memory locality because each context switch in a

method invocation may cause the working set of the called objects to be loaded into the main memory. The working sets of intermediate objects may need to be reloaded later when the return statement executes.

4.5 Refactored Solution 1. If you find the database access problem early in development, you may have the

option of selecting a different data organization in the database. A possible data restructuring approach is merging the tables in the database so as to reduce the number of required intermediate queries before obtaining the “ultimate results”. However, this may lead to tables that are not normalized.

Another approach is to provide views, which are constructed from the join operations of multiple tables in a database. The database will process queries to the constructed view instead of processing intermediate queries to individual table.

2. For distributed systems, if you cannot change the database organization, you can

reduce the number of remote database calls by using the Adapter pattern to provide a more reasonable interface for remote calls.

Instead of submitting a number of intermediate queries sequentially to the database, the set of all intermediate queries are submitted to the adapter at one time. The Adapter, which is located at the database, would then make all the other local database calls required to retrieve the “ultimate results”, and return only those results to the remote caller.

This reduces the number of remote calls and the amount of intermediate data transferred, but this does not reduce the database processing. This strategy can be found at Value Object Assembler.

Page 23: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

3. For the situations with large response sets, an alternative design approach is to create a new association that leads the remote caller directly to the “ultimate results”. Instead of passing the large response sets of data through objects to the remote caller, the large sets of data can be directly accessed by the remote caller. The performance impact is substantial if these are remote calls that are made via middleware such as CORBA or DCOM. This strategy can be found at Fast Lane Reader.

4.6 Example The Interactive Computer-Aided Design (ICAD) system illustrates the Circuitous Treasure Hunt AntiPattern [Smith and Williams 2001]. This application allows engineers to construct and view drawings that model structures, such as aircra ft wings. A model is stored in a relational database, and several versions of the model may exist within the database. Class Diagram of ICAD Figure 10 below shows a portion of the ICAD class diagram with the relevant classes. A model consists of elements that may be: beams, which connect two nodes; triangles, which connect three nodes; or plates, which connect at least four nodes. A node is defined by its position in the three-dimensional space (x, y, z).

Figure 10 ICAD Classes and Associations.

Page 24: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Problematic DrawMod scenario In the DrawMod scenario, a model is retrieved from the database and drawn on the screen. Figure 11 below shows a sequence diagram for this scenario. In this scenario, the software first finds the model ID, then uses it to find the beams, and repeats the sequence of steps to retrieve each beam row, using the node number from the beam row to find and then retrieve the node row, which contains the “ultimate results”—the node coordinates. This information is then used to draw the model on the screen. For a typical DrawMod scenario, there are 6001 database calls. One database call is for the model, 2000 calls for the beams, and 4000 calls for the nodes. An example DrawMod scenario The previous class diagram in Figure 10 above shows a simple example. Suppose that the model data has been retrieved from the database and is now contained within each Model object. Then the Model object must determine each Beam object to call from the association to Beam, and each Beam object must determine which Node objects to call from the association to Node s. The Model object calls the first Beam operation, then the Beam object calls two Node operations, and so on until all Node objects are retrieved. The resulting large number of database calls causes the most serious performance degradation in systems with remote database accesses, because of the high cost of the remote access, the processing of the queries, and the network transfer of all the intermediate results.

Figure 11 DrawMod Example of Circuitous Treasure Hunt.

Page 25: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Solution to DrawMod scenario The first solution to the problematic DrawMod scenario is reorganizing the data in the database. For example, the DrawMod database could store the node coordinates (x, y, z) in the Beam table. The sequence diagram for this alternative database design is shown in Figure 12 below. With the node coordinates in the beam row, the database call to find and retrieve node references from the Bean table is unnecessary and is omitted. For a typical DrawMod scenario with 2,000 beams, there will be 4,000 fewer database calls. However, it requires many considerations when trying to reorganize the data in the DrawMod database. Optimizing the data organization for one scenario may degrade the performance of other scenarios. To determine the appropriateness of each alternative data organization, the software engineer will need to analyze the performance impact on other scenarios that use the database. It is unwise to optimize the database organization for a single scenario if it has a performance degradation effect on all other scenarios. Indeed, we want the “globally optimal” solution for the important performance scenarios. To get this solution, we evaluate the overall performance by revising each scenario that is affected by the change in database organization.

Figure 12 Refactored DrawMod Scenario. Caller directly access “ultimate results” The second solution to the problematic DrawMod scenario is adding a direct association between the Model class and the Node class in the class diagram in Figure 10. This will allow the database caller to access directly from the Modal object to the Node objects contained in the Model. The “ultimate results” are those nodes in the modal that are associated with any Beam object. In the Draw-Mod scenario, this modification will reduce the number of database operations called from 6,000 (2000 Beam calls plus 4000 Node calls) to 1500 (the number of Nodes per Model).

Page 26: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Value Object Assembler Design Pattern The design strategies in the refactored solution of using the Adapter pattern have been applied in the Value Object Assembler Design Pattern of the Sun Java Center J2EE Patterns Release 1.0. The motivation of the Value Object Assembler Design Pattern is to solve problems in J2EE application models. An application model is an abstraction of the business data and business logic implemented on the server side as business components. The J2EE application model is a distributed collection of objects such as session beans, entity beans and data access objects. For a client to obtain data from the model in order to display data to the user or to perform some processing, it must access individually each distributed object that defines the model. One significant drawback is the performance degradation. The client accesses the distributed components via the network layer. This can lead to performance degradation if the model is complex with numerous distributed components. When a number of distributed business components implement the application model and the client directly interacts with these components to obtain the model data, each such access results in a remote method call that introduces network overhead. This will also increase the chattiness between the client and the business tier. It is desirable to minimize the number of remote method calls over the network. Value Objects Value Objects are commonly used to encapsulate the business data for data exchange between tiers in J2EE Design Patterns. The Value Object Assembler constructs a composite Value Object that represents the data from different business components [Alur et al. 2001]. The Value Object carries the data for the application model to the client in a single method call. When the client needs the model data, and if the model is represented by a single coarse-grained component, such as a Composite Entity in the data model, the client simply requests for the coarse-grained component. Assemble components into a composite Value Object and return to client However, most real-world applications have a model composed of a combination of many coarse-grained and fine-grained components. When multiple components are required to represent the entire application model, it is necessary to obtain Value Objects from the various components and assemble them into a new composite Value Object. The server, not the client, should perform such “on-the-fly” construction of the Value Object. The client will then obtain the assembled composite Value Object in a single method call.

Page 27: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

The following sequence diagram shows a typical scenario of the Value Object Assembler constructing a composite Value Object.

Figure 13 Value Object Assembler sequence diagram.

Page 28: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Merging Session Beans The design strategies in the refactored solution of using the Adapter pattern have also been applied in a J2EE Refactorings case study [Alur et al. 2001]. In the left part of Figure 14 below, the one-to-one mapping of a session bean to an entity bean introduces a layer of session beans acting as proxies. This is a typical bad practice when developers create session beans to front entity beans, rather than to represent coarse-grained services in the session beans. It is also shown in Figure 14 below that different clients are servicing different interactions. Each interaction involves one or more entity beans. With a one-to-one mapping of a session bean to an entity bean, the client has to interact with each session bean that fronts an entity bean. Since the session bean is essentially a proxy to the entity, this scenario is similar to exposing the entity bean directly to the client. Problem of exposing entity beans As entity beans mandate container-managed transaction, exposing the entity beans to the client may require the client developer to understand, design, and explicitly manage transactions when dealing with multiple entity beans. The client developer has to obtain a user transaction from the transaction manager and code the interactions with entity beans that occur within the context of that transaction. As the client implements the transaction management, it is not possible to use the benefits of container-managed transaction management.

Figure 14 Merging Session Beans. The right part of Figure 14 above shows the refactored solution. Instead of implementing each interaction with an entity bean by using a unique session bean, a set of related interactions that involve one or more entity beans is consolidated into a single Session Façade. This results in a fewer number of session beans that provide uniform coarse-grained business service accesses to entity beans. The number of Session Facades is related to the grouping of interactions but not to the number of entity beans.

Page 29: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Optimal granularity of the Session Façades When designing the Session Facades, we should analyze the interaction between the client and the application services, using use cases and scenarios to determine the coarseness of the Session Façades. The optimal granularity of the Session Façades for the application can be determined by partitioning the application into logical subsystems and providing a Session Façade for each subsystem [Matena and Stearns 2001]. For example, in Figure 14 above, client 1 only interacts with customer and project session beans while clients 2 and 3 interact with project and resource session beans. The Session Façade A is created as the component between client 1 and customer and project entity beans while the Session Façade B is created as the component between client 2 and project and resource entity beans.

Page 30: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Fast Lane Reader Design Pattern The design strategies to allow the direct access of large response sets of data returned by remote method calls is also applied in the Fast Lane Reader Pattern proposed by the J2EE BluePrints team[J2EE BluePrints 2001]. The Fast Lane Reader Pattern can accelerate the retrieval of large lists of items from a resource. Instead of going through an enterprise bean, an application accesses data more directly by going through a Data Access Object. In this way, the application avoids the overhead associated with using enterprise beans such as remote method invocation, transaction management and data serialization. Figure 15 below shows that the design pattern bypasses the EJB for read-only data access.

Figure 15 Fast Lane Reader. Read-only access example A typical example is the retrieval of the benefits of different staff in a company. To display the catalog of staff benefits, typical designs might have an EJB that represents the whole catalog. There might be a StaffBenefitsCatalogEJB that implements all required business logic related to the catalog, such as adding new benefits, removing an existing benefits or giving a list of staff benefits details to the requesting components. If other components request a list of staff benefits details, the requesting component will have to get a reference to the StaffBenefitsCatalogEJB, access the EJB 's remote method that gets the list of benefits, and then displays the catalog. This implementation method, while pr oviding transactional access for the required list of staff benefits, comes with the price of the overheads and remote calls associated with the use of the EJB. Given that the list of staff benefits is not going to change everyday, the chances of the staff obtaining outdated staff benefits information are low. Therefore, we don’t have to choose transactional access through the EJB and pay the associated price. As we can read the data directly rather than opting for transactional access, the Fast Lane Reader will be a more efficient way to access data. The Fast Lane Reader will give a faster response to the client while running a very small risk of displaying outdated data. By bypassing the EJB, the overheads associated with remote calls, transaction management, and other issues are avoided. A Java Servlet client that uses the Fast Lane Reader pattern will use the Data Access Object directly to read the list of staff benefits and then display the list.

Page 31: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

However, it should be reminded that the problem domain that was described in the scenario of Fast Lane Reader requires only read access to a set of data that does not change rapidly and so this pattern is good for faster and more efficient data retrieval only [Ramachandran 2001]. For updating the data, this pattern should not be used because transactional access is bypassed.

Page 32: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

5. Excessive Dynamic Allocation

5.1 AntiPattern Name: Excessive Dynamic Allocation

5.2 General Form With dynamic allocation, objects are created when they are first accessed and then destroyed when they are no longer needed. This may be a good approach to structuring a system as it provides flexibility in highly dynamic situations. For example, in a graphics editor, it may be a very useful approach to create an instance of a shape such as a circle or rectangle when it is drawn, and destroy the instance when the shape is deleted. Excessive Dynamic Allocation, however, causes frequent, unnecessary creation and destruction of objects of the same class. As dynamic allocation is expensive, these unnecessary actions will consume much resources of the system.

5.3 Symptoms and consequences 1. When an object is created, the memory to contain the new object and any objects

that the new object contains must be allocated from the heap, and any initialization code for the object and the contained objects must be executed.

2. When the object is no longer needed, necessary resources clean-up must be

performed, and the reclaimed memory must be returned to the heap to avoid “memory leaks”. Therefore, many objects of the same class in the system are temporary and are of short durations.

3. While the overhead for creating and destroying a single object may be small, the

performance degradation may be significant when a large number of objects are frequently created and then destroyed in a short time.

5.4 Typical Causes of the Problem 1. A complex object contains some other objects, which can also contain objects.

Therefore, the allocation of a complex object may involve allocating memory to many other objects and the memory allocated can be significant.

2. The de-allocation of a complex object and the objects inside it should also be

handled carefully to prevent from the dangling pointers. Not only the memory allocation and de -allocation of temporary objects consume resources, maintaining the transient associations among the short-lived objects and long-lived objects also consume system resources.

Page 33: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

5.5 Refactored Solution There are two possible solutions to the Excessive Dynamic Allocation AntiPattern:

1. The first solution is to “recycle” object instances rather than create new object instances each time the instances are needed. This approach pre-allocates a “pool” of object instances and stores them in a collection. New instances of the required object are requested from the pool, and unneeded instances are returned to the pool. This approach is useful for systems that continually need many short-lived objects such as the phone call processing application.

We have to pay resources for pre-allocating the object instances at system initialization but reduce the run-time overhead to simply passing a pointer to the pre-allocated instance when a new object instance is requested. Returning unused instances to the pool eliminates garbage collection overhead and possible memory leaks. This strategy is applied in life cycle of Entity Beans and pooling database connections .

2. Another refactored solution for the Excessive Dynamic Allocation AntiPattern is

to share object instances rather than create new object instances when a new object instance is requested. This may be possible in certain situations when the requested instances do not store any information particular to the caller who request a new object instance. This strategy is also applied in converting stateful beans into stateless beans.

The first improvement approach affects the cost of excessive dynamic allocation by reducing the object request service time to the time for allocating/returning an object instance from/to the pool. Only one object instance is required to be selected from the pool on each object allocation request because the pre-allocated object instances in the pool have already created the subordinate object instances. The improvement for the second approach is similar.

Page 34: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

5.6 Example

Figure 16 Excessive Dynamic Allocation. Example scenario The sequence diagram in Figure 16 above illustrates the Excessive Dynamic Allocation AntiPattern [Smith and Williams 2001]. This example is drawn from a phone call processing application in which, when a customer lifts the telephone handset (an offHook event occurs), the switch creates a Call object to manage the call. When the call is completed (an onHook event occurs), the Call object is destroyed. A Call object is a complex object that contains several other objects. These contained objects must also be created when the Call object instance is constructed. In addition, a switch can receive hundreds of thousands of offHook events each hour and so the construction and destruction of Call object instances have to be frequently performe d. In this case, the overhead for dynamically allocating Call object instances adds substantial delays to the time needed to complete a call. Refactored solution to the example The refactored solution to the AntiPattern in this example is recycling Call object instances. If we pre-allocate a block of Call object instances instead of creating them dynamically, we can save the unnecessary overhead for dynamically allocating Call object instances. Each call object instance is used over and over again, rather than creating a new one for each offHook event.

Page 35: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Life Cycle of Entity Bean Instance The pooling strategy is also used in the aspect of the Enterprise JavaBeans. The life cycle of an Entity Bean Instance is shown in the Figure 17 below. The Entity Bean Instance is in the pooled state after the passivation invoked by the container. The container will passivate the Entity Bean Instance when the EJB container needs to reclaim the resources held by the instance [Matena and Stearns 2001]. Passivation of an Entity Bean instance The container will first invoke the ejbStore method on the instance. If the Entity Bean instance is Bean-Managed, it will write any cached updates made to the entity object state to the database. If the Entity Bean instance is Container -Managed, the container will update the object state in the database with the extracted values of the CMP fields in the entity instance. In both cases, the container will then invoke the ejbPassivate method in the Entity Bean instance to migrate it to the pooled state. The instance should release any resources that it does not need before it is migrated into the pooled state. The container may activate the instance in the pooled state for another object identity. Reactivation of an Entity Bean instance When the client invokes another business method on the entity object, the entity object allocates an instance from the pool. The allocated instance could be the same instance or a different instance than the one that was associated with the object identity prior to passivation. The container then invokes the ejbActivate method in the Entity Bean instance. If the Entity instance is Bean-Managed, the container invokes the ejbLoad method in the instance to read the object state, or parts of the object state, from the database. If the instance is Container-Managed, the container reads the object state from the database, sets the CMP fields of the instance with the values read from the database and finally the container invokes the ejbLoad method in the instance. After that, the entity object can delegate the requested business method to the reactivated entity instance.

Figure 17 Life Cycle of an Entity Bean Instance.

Page 36: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Pooling database connections As the entity bean instances have to release resources when they are passivated, the database connections may be acquired and released multiple times when a number of database queries are processed. As shown in Figure 18 below, acquiring and releasing database connections via the database manager, using JDBC 1.0, will impact adversely the performance on the EJB layer [Visveswaran 2000]. This adverse impact is due to the overhead in creating and destroying those connection objects by the database resource manager process. Typically, the application server process takes around one to three seconds to establish a database connection that includes communicating with the server, authenticating, and so forth, and that needs to be done for every client or EJB request.

Figure 18 Connection management using JDBC 1.0. JDBC 2.0 Standard Extension API and JDBC 3.0 Connection pooling is a technique that was pioneered by database vendors to allow multiple clients to share a cached set of connection objects that provide access to a database resource. The JDBC 2.0 Standard Extension API specifies that a database service provider can implement the connection pooling technique that can allow multiple connection objects from a resource pool to be shared transparently among the requesting clients. In this situation, a J2EE component can use connection objects without causing overheads on the database resource manager, because a pool manager creates the connection objects upfront, at the star tup. The application server implements the pool manager in its memory space and can optimize resource usage by dynamically altering the pool size, based on demand. This is illustrated in Figure 19 below. Using the javax.sql.DataSource interface (JDBC 2.0), a J2EE component could get an already open connection from the pool, and eventually releases the connection back to the pool when its usage terminates.

Page 37: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Figure 19 Connection pooling using JDBC 2.0 Standard extension. The JDBC 3.0 specification introduces the new feature of statement pooling [JDBC 2001]. This new feature, which allows an application to reuse a PreparedStatement object in much the same way as it can reuse a connection, is made available through a pooled connection. Figure 20 below provides a logical view of how a pool of PreparedStatement objects can be associated with a PooledConnection object. As with the PooledConnection object itself, the PreparedStatement objects can be reused by multiple logical connections in a completely transparent manner. Statements are kept open for reuse entirely under the cover, the only visible effect of statement pooling is a possible improvement in performance for complex prepared statements.

Figure 20 Logical view of prepared statements reused by pooled connections.

Page 38: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

Converting stateful session beans into stateless session beans The session beans employed in any J2EE infrastructure can be either stateless or stateful. However, stateless session beans are much more efficient than stateful session beans. A stateless session bean is a very lightweight bean, as it needs to carry around only EJB-mandated variables, but not programmer-defined ones. As a result, most EJB containers have pools of stateless beans . Because no single client needs to have access to a specific stateless bean instance, a single stateless bean instance can serve a large number of clients. This allows the bean pool to be kept small, and prevents from a frequent need to grow or shrink the pool, which would consume valuable CPU power. On the other hand, when using stateful beans, each stateful bean instance is tied to the client that invoked its create() method. This means that an instance must exist for every client accessing the stateful bean. Therefore, the bean pools must be larger, or must frequently be grown as more requests from new clients come in. The end result is longer processing times, more beans, and fewer clients being served. In short, if at all possible, we should use state less session beans. Details of the conversion The J2EE infrastructure typically requires a stateful session bean to implement a conversational business process. The article by Brett McLaughlin demonstrates how a stateful session bean can be converted into a stateless session bean [McLaughlin 2002] . In order to substitute a stateful session bean with a stateless session bean, the stateless session bean will have a counterpart Helper class. The Helper class maintains a stateless session bean instance, the “state” information of the corresponding stateful session bean, and a mirror remote interface of the stateful session bean. The encapsulated stateless session bean also has the same interface as that of the stateful session bean. In this case, all the methods calls and interactions with the original stateful session bean are replaced with the corresponding ones in the mirror interface at the Helper class, which will interact with the encapsulated stateless session bean. All the same exceptions are passed through to the client. The only difference to the client is that the initial context lookups are handled by the Helper class. This approach provides the best of both session bean types: the performance of a stateless be an with the interface of a stateful bean. Figure 21 below shows the structure of the Helper Class. Figure 21 Structure of Helper Class

Mirror Interface

State Information

Stateless Session Bean

Client

Helper Class

Page 39: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

6. Conclusion We have already discussed four Software Architecture AntiPatterns, the solutions to these AntiPatterns and also the ways to apply the strategies in these solutions. AntiPatterns are necessary for us to gain an understanding of common problems faced by most software developers. Learning from other developers’ successes and failures is valuable and necessary. Without this wisdom, AntiPatterns will continue to persist.

Page 40: COMP610E Software Development of E-Business Applications · AntiPatterns: Stovepipe System, Vendor Lock-In, Circuitous Treasure Hunt and Excessive Dynamic Allocation. The AntiPatterns

7. References [Brown et al. 1998] W. J. Brown, R. C. Malveau, H. W. McCormick III, and T. J.

Mowbray, AntiPatterns: Refactoring Software, Architectures, and Projects in Crisis, New York, John Wiley and Sons, Inc., 1998.

[Smith and Williams 2001] L.G. Williams and C.U. Smith, Performance Solutions: A

Practical Guide to Creating Responsive, Scalable Software, Addison-Wesley, Reading, MA, 2001.

[Alur et al. 2001] D. Alur, J. Crupi and D. Malks, Core J2EE Patterns: Best Practices and

Design Strategies, U.S.A., Sun Microsystems, Inc., 2001. [Matena and Stearns 2001] V. Matena, B. Stearns, Applying Enterprise JavaBeans:

Component-Based Development for the J2EE Platform. Addison-Wesley, 2001. [Visveswaran 2000] S. Visveswaran, “Dive Into Connection Pooling With J2EE Manage

Access to Shared, Server-Side Resources for High Performance”, JavaWorld, October 2000.

[JDBC 2001] J. Ellis & L. Ho and M. Fisher, JDBC 3.0 Specification Final Release,

Sun Microsystems, Inc., October 2001. [McLaughlin 2002] B. McLaughlin, Building Java Enterprise Applications:

Business Logic, Part 3, in Building Java Enterprise Applications vol I: Architecture, OREILLY, March 2002.

[Ramachandran 2001] V. S. Ramachandran, “Design Patterns for Optimizing the

Performance of J2EE Applications”, Java Developer ’s Journal, December 2001. [J2EE BluePrints 2001] J2EE BluePrints team, J2EE Design Patterns,

Sun Microsystems, Inc., 2001. [Brown et al. 1999] W. J. Brown, H. W. McCormick III, and S. W. Thomas,

AntiPatterns and Patterns in Software Configuration Management, New York, John Wiley and Sons, Inc., 1999.