Home > Articles > Programming > Java

This chapter is from the book

3.4. Modularity: The Missing Ingredient

Two of the key elements of the architectural definitions are component and composition. Yet there is no standard and agreed-upon definition of component1 (reminding me of architecture, actually), and most use the term loosely to mean “a chunk of code.” But, that doesn’t work, and in the context of OSGi, it’s clear that a module is a software component. Developing a system with an adaptive, flexible, and maintainable architecture requires modularity because we must be able to design a flexible system that allows us to make temporal decisions based on shifts that occur throughout development. Modularity has been a missing piece that allows us to more easily accommodate these shifts, as well as focus on specific areas of the system that demand the most flexibility, as illustrated in Figure 3.5. It’s easier to change a design encapsulated within a module than it is to make a change to the design than spans several modules.

Figure 3.5.

Figure 3.5. Encapsulating design

3.4.1. Is It Really Encapsulated?

In standard Java, there is no way to enforce encapsulation of design details to a module because Java provides no way to define packages or classes that are module scope. As a result, classes in one module will always have access to the implementation details of another module. This is where a module framework, such as OSGi, shines because it allows you to forcefully encapsulate implementation details within a module through its explicit import package and export package manifest headers. Even public classes within a package cannot be accessed by another module unless the package is explicitly exported. The difference is subtle, although profound. We see several examples of this in the patterns throughout this book, and I point it out as it occurs. For now, let’s explore a simple example.

3.4.1.1. Standard Java: No Encapsulation

Figure 3.6 illustrates a Client class that depends upon Inter, an interface, with Impl providing the implementation. The Client class is packaged in the client.jar module, and Inter and Impl are packaged in the provider.jar module. This is a good example of a modular system but demonstrates how we cannot encapsulate implementation details in standard Java because there is no way to prevent access to Impl. Classes outside of the provider.jar module can still reach the Impl class to instantiate and use it directly.

Figure 3.6.

Figure 3.6. Standard Java can’t encapsulate design details in a module.

In fact, the Impl class is defined as a package scope class, as shown in Listing 3.1. However, the AppContext.xml Spring XML configuration file, which is deployed in the client.jar module, is still able to create the Impl instance at runtime and inject it into Client. The App-Context.xml and Client class are shown in Listing 3.2 and Listing 3.3, respectively. The key element is that the AppContext.xml is deployed in the client.jar module and the Impl class it creates is deployed in the provider.jar module. As shown in Listing 3.2, the AppContext.xml file deployed in the client.jar file violates encapsulation by referencing an implementation detail of the provider.jar module. Because the Spring configuration is a global configuration, the result is a violation of encapsulation.

Listing 3.1. Impl Class

package com.p2.impl;

import com.p2.*;

class Impl implements Inter {
      public void doIt() { . . . /* any implementation */ }
}

Listing 3.2. AppContext.xml Spring Configuration

<beans>
    <bean id="inter" class="com.p2.impl.Impl"/>
</beans>

Listing 3.3. Client Class

package com.p1;

import com.p2.*;
import org.springframework.context.*;
import org.springframework.context.support.*;

public class Client {
   public static void main(String args[]) {
      ApplicationContext appContext = new
      FileSystemXmlApplicationContext(
         "com/p1/AppContext.xml");
      Inter i = (Inter) appContext.getBean("inter");
      i.doIt();
   }
}

3.4.1.2. OSGi and Encapsulation

Now let’s look at the same example using OSGi. Here, the Impl class in the provider.jar module is tightly encapsulated, and no class in any other module is able to see the Impl class. The Impl class and Inter interface remain the same as in the previous examples; no changes are required. Instead, we’ve taken the existing application and simply set it up to work with the OSGi framework, which enforces encapsulation of module implementation details and provides an intermodule communication mechanism.

Figure 3.7 demonstrates the new structure. It’s actually an example of the Abstract Modules pattern. Here, I separated the Spring XML configuration into four different files. I could have easily used only two configuration files, but I want to keep the standard Java and OSGi framework configurations separate for each module. The provider.jar module is responsible for the configuration itself and exposing its capabilities when it’s installed. Before we describe the approach, here is a brief description of each configuration file:

Figure 3.7.

Figure 3.7. Encapsulating design with OSGi

  • client.xml: Standard Spring configuration file that describes how the application should be launched by the OSGi framework
  • client-osgi.xml: Spring configuration file that allows the Client class to consume an OSGi μService
  • provider.xml: Spring configuration with the provider.jar module bean definition
  • provider-osgi.xml: Spring configuration that exposes the bean definition in provider.xml as an OSGi μService

Before we look at how the two modules are wired together, let’s look at the provider.jar module, which contains the Inter interface, Impl implementation, and two configuration files. Again, Inter and Impl remain the same as in the previous example, so let’s look at the configuration files. The provider.xml file defines the standard Spring bean configuration and is what was previously shown in the AppContext.xml file in Figure 3.7. Listing 3.4 shows the provider.xml file. The key is that this configuration is deployed with the provider.jar module. Attempting to instantiate the Impl class outside of the provider.jar module will not work. Because OSGi enforces encapsulation, any attempt to reach the implementation details of a module will result in a runtime error, such as a ClassNotFoundException.

Listing 3.4. provider.xml Configuration File

<beans>
       <bean id="inter" class="com.p2.impl.Impl"/>
</beans>

How does OSGi prevent other classes from instantiating the Impl class directly? The Manifest.mf file included in the provider.jar module exposes classes only in the com.p2 package, not the com.p2.impl package. So, the Inter interface registered as an OSGi μService is accessible by other modules but not by the Impl class. Listing 3.5 shows the section of the Manifest.mf illustrating the package export.

Listing 3.5. provider.xml Configuration File

Export-Package: com.p2

The provider-osgi.xml file is where things get very interesting, and it is where we expose the behavior of the provider.jar module as an OSGi μService that serves as the contract between the Client and Impl classes. The configuration for the provider.jar module lives within the provider.jar module, so no violation of encapsulation occurs.

Listing 3.6 shows the configuration. The name of the μService we are registering with the OSGi framework is called interService, and it references the Impl bean defined in Listing 3.4, exposing its behavior as type Inter. At this point, the provider.jar module has a interService OSGi μService that can be consumed by another module. This service is made available by the provider.jar module after it is installed and activated in the OSGi framework.

Listing 3.6. provider.xml Configuration File

<osgi:service id="interService" ref="inter"
      interface="com.p2.Inter"/>

Now, let’s look at the client.jar module. The client.xml file configures the Client class. It effectively replaces the main method on the Client class in Listing 3.3 with the run method, and the OSGi framework instantiates the Client class, configures it with an Inter type, and invokes the run method. Listing 3.7 shows the client.xml file, and Listing 3.8 shows the Client class. This is the mechanism that initiates the process and replaces the main method in the Client class of the previous example.

Listing 3.7. Client.xml Configuration File

<beans>
      <bean name="client" class="com.p1.impl.Client"
      init-method="run">
                  <property name="inter"
                   ref="interService"/>
        </bean>
</beans>

Listing 3.8. The Client Class

package com.p1.impl;
import com.p2.*;
import com.p1.*;
public class Client {
      private Inter i;
      public void setInter(Inter i) {
            this.i = i;
      }

      public void run() throws Exception {
            i.doIt();
      }
}

The Inter type that is injected into the client class is done through the client-osgi.xml configuration file. Here, we specify that we want to use a μService of type Inter, as shown in Listing 3.9.

Listing 3.9. Client.xml Configuration File

<osgi:reference id="interService"
 interface="com.p2.Inter"/>

The Manifest.mf file for the client.jar module imports the com.p2 packages, which gives it access to the Inter μService. Listing 3.10 shows the section of Manifest.mf showing the package imports and exports for the client.jar module.

Listing 3.10. Client.xml Configuration File

Import-Package: com.p2

This simple example has several interesting design aspects.2 The provider.jar module is independently deployable. It has no dependencies on any other module, and it exposes its set of behaviors as a μService. No other module in the system needs to know these details.

The design could have also been made even more flexible by packaging the Impl class and Inter interface in separate modules. By separating the interface from the implementation, we bring a great deal of flexibility to the system, especially with OSGi managing our modules.

At first glance, it might also appear to contradict the External Configuration pattern. When defining the external configuration for a module, we still want to ensure implementation details are encapsulated. External configuration is more about allowing clients to configure a module to its environmental context and not about exposing implementation details of the module.

The key takeaway from this simple demonstration is that the classes in the provider.jar module are tightly encapsulated because the OSGi framework enforces type visibility. We expose only the public classes in the packages that a module exports, and the μService is the mechanism that allows modules to communicate in a very flexible manner. The μService spans the joints of the system, and because OSGi is dynamic, so too are the dependencies on μServices. Implementations of the μService can come and go at runtime, and the system can bind to new instances as they appear.

Again, we’ll see several more examples of this throughout the remainder of the discussion. Even though you can’t enforce encapsulation of module implementation using standard Java, it’s still imperative to begin designing more modular software systems. As we’ll see, by applying several of the techniques we discuss in this book, we put ourselves in an excellent position to take advantage of a runtime module system.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020