Welcome!

Websphere Authors: Carmen Gonzalez, Roger Strukhoff, Ajay Budhraja, Mustafa Kapadia, Lori MacVittie

Related Topics: Java, XML, SOA & WOA, Websphere, Weblogic, AJAX & REA, Apache

Java: Article

Componentizing a Monolithic Application in Java

Using a simple homegrown component model and framework

Component-oriented development has many architectural advantages. In spite of this, many developers tend to solve problems the monolithic way on the first go. This article demonstrates how a monolithic design can be modified to achieve component-based design. During this conversion process, the necessity of Component Models and Frameworks are highlighted. The article demonstrates the componentization of an example monolithic application using a simple homegrown component model and framework developed by the authors.

Introducing E-Store - A Business Application
Let us assume that we need to implement a simple E-store business application. The application needs to cater to the following simple business use cases for a single actor - the consumer.

  • Browse the catalog of products - Consumer can browse through the items in the store. E-store app displays the different products available in the store along with their price
  • Buy one or more products - User adds one or more quantities of a product to the shopping cart. If sufficient stock is available, E-Store app adds the selected items to the shopping cart
  • Check-out - User can checkout with the items in the shopping cart. E-store app displays the total price of all the items in the shopping cart. Subsequently, stock quantities of the purchased items are reduced

Monolithic Implementation of E-Store
The E-Store application explained above can be realized with the help of the classes shown in Figure 1.

Figure 1: Class Diagram for E-Store Application

The implementation of the above design in source code and binary code form can be obtained from the links provided at the end of the article. The implementation of the monolithic application is explained briefly in the sections below.

Application Startup - UI
The monolithic E-Store application starts up with the UI class main method. During its startup, the UI class instantiates the Store (E-Store) class. The code snippet corresponding to this is shown in Listing 1.

public class UI {

static Store estore = new Store();

public static void main(String[] args) {
int userChoice = mainMenu();
...
}
...
}

Listing 1: Startup Code - UI Class

The E-Store class instantiates the Inventory and ShoppingCart classes during its startup as shown in Listing 2.

public class Store {

Inventory inventory = new Inventory();
ShoppingCart shoppingCart = new ShoppingCart();
...
}

Listing 2: Startup Code - E-Store Class

The inventory class initializes the stock during its instantiation, by creating instances of Product class objects. The code snippet is shown in Listing 3

public class Inventory {

private Map<Product, Integer> stock = new HashMap<Product, Integer>();

public Inventory() {initStock();}

private void initStock() {
Product newIPad = new Product("NewIPad", 400.00);
stock.put(newIPad, 50);

Product galaxyTab2 = new Product("GalaxyTab2", 300.00);
stock.put(galaxyTab2, 75);

Product kindleFire = new Product("KindleFire", 250.00);
stock.put(kindleFire, 30);
}
...

}

Listing 3: Startup Code - Inventory Initialization

Once the startup is done, the UI class presents a console based menu as shown in Listing 4.

Welcome to eStore!
------------------------

1. Browse Catalog
2. Buy Items
3. Check Out
4. Exit

Choose an option:
1

Listing 4: Console based UI Menu

When the user chooses any one of the options, the UI class calls upon its implementation in the E-Store business class. The implementation of each of these is explained briefly in next few sections.

Browse Catalog Use case Realization
The getCatalog() method in the E-Store class implements this use case. When the getCatalog() method in E-Store class is called, it fetches the list of products from Inventory and returns the same. Code snippet is shown in Listing 5.

public Collection<Product> getCatalog() {

return inventory.getProducts();

}

Listing 5: E-Store Class - getCatalog() implementation

Buy Items Use case Realization
The buyItem() method in the E-Store class implements this use case. The UI class calls this method by passing the name of the product chosen by the user, and the quantity he wants to buy. If sufficient quantity is available in stock, the item is added to the shopping cart and the method returns success; otherwise, the method returns failure and no item is added to shopping cart. The code snippet is presented in Listing 6.

public boolean buyItem(String name, int quantity) {
Product product = inventory.getProduct(name);
if (product == null) return false;

if (inventory.getStock(product) >= quantity) {
shoppingCart.addItem(product, quantity);
return true;
}
return false;
}

Listing 6: E-Store Class - buyItem() implementation

Check Out Use Case Realization
The checkout() method in the E-Store class implements this use case. It reduces the stock in the inventory by the quantity bought. It also returns the total price to be paid by the user. This implementation is shown in Listing 7.

public double checkOut() {
for(Product product : shoppingCart.getItems()) {
int quantity = shoppingCart.getCount(product);
inventory.reduceStock(product, quantity);
}
double price = shoppingCart.getTotalPrice();
shoppingCart.clearItems();
return price;

}

Listing 7: E-Store Class - checkOut() Implementation

What's wrong with the Monolithic implementation?
The initial implementation of E-Store discussed above fulfills all the functional requirements of the application laid down earlier. Still this is not considered as architecturally sound application design because all the classes in the application are tightly coupled to each other. Consider the dependency metrics shown in the table below:

Table 1: Class dependency details

No.

Class

Depends On

# of Dependencies

Dependency Depth

1.

Product

 

0

0

2.

Inventory

Product

1

1

3.

ShoppingCart

Product

1

1

4.

EStore

Inventory, ShoppingCart, Product

3

2

5.

UI

EStore, Product

2

3

 

 

 

 

 

The tight coupling results in high resistance to change in implementation. For example, any change to Product class will require complete change in the application.

Let us say that the E-Store likes to announce promotional sale for three days. During these three days, the total price of the shopping cart should be discounted by 10%. In order to achieve this, we need to change the ShoppingCart class implementation. When the ShoppingCart class is changed, the E-Store class also needs to be recompiled. When the E-Store class is recompiled, the UI class also needs to be recompiled.

What happens at the end of the promotional sale when the E-Store wants to discontinue the discounts? We need to recompile all the 3 classes one more time. Ideally, since the changes affect only the ShoppingCart behavior, rest of the application modules should not have been affected. But due to the tight coupling, other modules are also affected.

Loosening the Coupling through Componentization
Low coupling design principle suggests that there should not be tight coupling among unstable entities. Having dependency on a relatively stable entity does not bring forth the evils of tight coupling.

In order to make the application modules loosely coupled, we need to componentize the application. A component is a deployable piece of software that would be independently developed and independently maintained. Independence here refers to development and maintenance of a component independent of the other components which collaborate with this component in an application assembly. In a component based application, change to one component should not directly affect the application.

We avoid tight coupling between components by introducing the abstraction of Component Interface. A component interface exposes the signature of the functionalities implemented by component. The Component Interface will be a relatively stable entity as compared to the Component Implementation.

A component consumes interfaces that it depends on for fulfilling the required functionality and provides interfaces for the functionality it provides. For collaboration with the other components, the component would work through the interfaces provided by the other components. Practically, the component should not depend on the implementation of the other components; it should depend only on the interfaces provided by those components. This way, the coupling among components is through the relatively stable interfaces and not through the highly instable implementations. Thus the principle of low coupling is upheld.

In addition to the low coupling achieved, componentization of a monolithic application also brings about substitutability of components. This means a component of the application can be substituted by another component without affecting the overall application. The only requirement is that the replacing component must offer the same set of interfaces as was offered by the component being replaced.

Componentizing the E-Store Application
We need to introduce the Component Interface abstraction in the monolithic design shown in Figure 1. Looking at the dependency details represented in the Table 1, the Product, ShoppingCart, Inventory and Store classes should be represented as components. From the implementation classes of Product, Inventory, ShoppingCart, and Store, we can extract Java Interfaces IProduct, IInventory, IShoppingCart, and IStore respectively using the refactoring tools in the IDE. The extracted interfaces are shown in Figure 2. It must be noted in Figure 9 that the method signatures in IInventory, IShoppingCart, and IStore are changed to refer to IProduct interface in place of the Product class in the corresponding methods in Figure 1.

Figure 2: E-Store Interfaces - Class Diagram

In this E-Store application, there are four components represented by their interfaces - IProduct, IInventory, IShoppingCart and IStore. After the interfaces are extracted from the monolithic implementation, it will be a good design to get these interfaces packaged into a separate Java Package called estore.ifce.

The package can also be compiled to a JAR resulting in a deployable and independently maintainable estore.ifce module. This module does not implement any component, but it simply defines ONLY the interfaces which would be implemented by other components in the application. All the components depend ONLY on this common interface module and they need not depend on individual implementation components.

Following the above principle, if we separate the implementation of Product, Inventory, ShoppingCart, and Store into individual packages and into individual JARs, we get the  package structure shown in Figure 3.

Figure 3: Package Diagram separating interface from implementation

When we refactor the code into multiple components as shown above, two code segments fail to compile as shown in Figure 4 and Figure 5. Kindly look at Listings 2 and 3 for reference.

Figure 4: Compilation error in Inventory class post Componentization

Figure 5: Compilation error in Store class post Componentization

The compilation errors occurred due to the fact that above code tried to invoke the implementation code of other components directly. We have arranged our dependencies such that one component would not depend on the internal implementation of the other component. The above code violates this.

This problem can be solved in various ways. This is where all the component models and frameworks come to the rescue. Component models like RMI, EJB, Spring, OSGi and SCA have their own way of creating object references to components from the interfaces. Users can choose to use one of these frameworks or models for initializing the component. However in this article, we will look at a simple component model developed to solve this problem without using any of the component models and frameworks. This component model uses some of the principles of design pattern and best practices which is explained in detail below.

The problem of direct reference to implementation can be resolved by introducing a ‘Factory' object that can be used by the component to obtain an object of the corresponding type. A generalized Factory object could have a signature as below:

public interface IFactory<T> {
public T createInstance();

}

To avoid tight coupling, the Factory object is really useful. So, instead of coupling to a concrete class which implements IProduct, the Inventory implementation can depend on a Factory object of type IFactory<IProduct>. By invoking the createInstance() method on the factory object, the Inventory class can obtain new IProduct objects. Similarly the IInventory and IShoppingCart objects can be obtained from the respective Factory objects using createInstance() method in the Store class.

IProduct iPad = productFactory.createInstance();
.....
IShoppingCart shoppingCart = shoppingCartFactory.createInstance();
IInventory inventory = inventoryFactory.createInstance();

To obtain a factory object, a FactoryRegistry class is used as a common factory registry for registering and retrieving factory objects using the whiteboard pattern. The common registry object can be implemented as shown in Listing 8.

public class FactoryRegistry {

private static Map<Class<?>, IFactory<?>> factoryMap = new HashMap<Class<?>, IFactory<?>>();

public static void registerFactory(Class<?> ifceClazz, IFactory<?> factory) {
factoryMap.put(ifceClazz, factory);
}

public static IFactory<?> getFactory(Class<?> ifceClazz) {
return factoryMap.get(ifceClazz);
}
}

Listing 8: FactoryRegistry Class

The Inventory class can obtain a reference to a product factory object of type IFactory<IProduct> using the whiteboard pattern. Similarly any factory object can be retrieved from the FactoryRegistry.

IFactory<IProduct> productFactory =
(IFactory<IProduct>) FactoryRegistry.getFactory(IProduct.class);

One important question that remains unanswered is how, where and when these factory objects are registered with the FactoryRegistry. All component implementations only try to GET references. As mentioned earlier, component models like RMI, EJB, OSGi have their own service repository where these references are registered and components using these references look up the repository to get an object of the corresponding type. In this simple model, a registry program named ‘ComponentRunner' is handwritten which will look up for IFactory type interfaces and its implementations and register them appropriately so that getFactory method returns an initialized factory object. Kindly refer to the source code provided for details on ComponentRunner.

Implementation of this model will help in resolving the compilation issue highlighted in Figures 4 and 5. The modified code without any compilation error using the factory pattern and registry lookup is shown in Listings 9 and 10.

private void initStock() {

IFactory<IProduct> productFactory = (IFactory<IProduct>) FactoryRegistry.getFactory(IProduct.class);

IProduct iPad = productFactory.createInstance();
iPad.setName("NewIPad");
iPad.setPrice(400.00);
stock.put(iPad, 50);

IProduct gTab = productFactory.createInstance();
gTab.setName("GalaxyTab2");
gTab.setPrice(300.00);
stock.put(gTab, 75);

IProduct kindle = productFactory.createInstance();
kindle.setName("KindleFire");
kindle.setPrice(250.00);
stock.put(kindle, 30);

}

Listing 9: Modified Inventory Class without compilation error

public class Store implements IStore {

IInventory inventory;
IShoppingCart shoppingCart;

public Store() {
IFactory<IInventory> inventoryFactory = (IFactory<IInventory>) FactoryRegistry.getFactory(IInventory.class);
IFactory<IShoppingCart> shoppingCartFactory = (IFactory<IShoppingCart>) FactoryRegistry.getFactory(IShoppingCart.class);

shoppingCart = shoppingCartFactory.createInstance();
inventory = inventoryFactory.createInstance();
}
......

Listing 10: Modified E-Store Class without compilation error

Apart from the above highlighted modifications, the business logic implementation in the components remains the same as before in the monolithic case.

Executing the Sample Application
The sample application demonstrated in this article is available as a zip file for download. The zip file contains a complete Eclipse Workspace with the source as well as binary files. To run the componentized version of this application, it is required to follow the steps below:

  1. Create a folder named ‘run'.
  2. Export the components - store, product, inventory, shopping cart, component model, store app projects from the eclipse workspace to a Jar file in the ‘run' folder, say ‘eStore.jar' for example. In order to reuse these components in other applications, individual projects can be exported as separate jar files.
  3. Copy the contents of ‘bin' folder from comprunner project to the ‘run' folder. The bin folder contains a sub folder named ‘comprunner' which contains the ComponentRunner class.
  4. Open a command prompt and change the directory to ‘run' folder.
  5. To execute the ComponentRunner, type the following in command prompt

Conclusion
The advantage of a component-oriented approach is well explained with a sample application. In this article, we also saw the limitations of having a monolithic application and how the dependencies bring in tight coupling between components. Low coupling between components can be achieved by the abstraction of Component interface. Interfaces also bring in component substitutability. A component can depend on some interfaces and provide interfaces. Interface is the key mechanism in component design principles. Initialization of component implementations can happen using several mechanisms which are different for different component models and frameworks. In this sample, a home grown component model - a factory based model is used for initializing the components and component references are registered with a simple repository - CompRunner for look up.

More Stories By Piram Manickam

Piram Manickam works at Infosys Limited. He would like to acknowledge and thank Sangeetha S, a beloved colleague and friend, for her invaluable contributions in this work.

More Stories By Subrahmanya SV

Subrahmanya SV works at Infosys Limited. He would like to acknowledge and thank Sangeetha S, a beloved colleague and friend, for her invaluable contributions in this work.

More Stories By S Sangeetha

S Sangeetha is a Senior Technical Architect at the E-Commerce Research Labs at Infosys Limited. She has over 15 years of experience in architecture, design and development of enterprise Java applications. She is also involved in enhancing the technical skills of Architects at Infosys. She has co-authored a book on ‘J2EE Architecture’ and also has written numerous articles on Java for various online Java forums like JavaWorld, java.net, DevX.com and internet.com. She can be reached at sangeethas@infosys.com.

Comments (1)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, will describe how to revoluti...
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
SYS-CON Events announced today that SOA Software, an API management leader, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that Utimaco will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.