Java IoT Authors: Elizabeth White, Scott Allen, Liz McMillan, Roger Strukhoff, Kevin Benedict

Related Topics: Java IoT

Java IoT: Article

Evolving Functionality

Evolving Functionality

C++ brought into vogue the concept of interfaces, abstractness, and implementations. Java went a step further and formalized them with proper keywords for each of the concepts. There are a substantial number of patterns in which interfaces, abstract classes, and classes can be combined for various purposes. You only have to look at the book Design Patterns, by Erich Gamma et al (Addison-Wesley), to realize the importance of recognizing these constructs.

Constructing a software program that you expect to have a long life is an attempt to evolve its functionality over time, without abandoning older behavior for backward compatibility. This is a lot more essential when you're designing libraries and frameworks. The newer libraries should work with older systems that were designed for the older releases of a library. Here are some concrete examples of why this is important and how to accomplish this in situations where every programmer is encouraged to adapt the scheme owing to its simplicity.

What Is Evolving Functionality?
To understand what evolving functionality is, let's walk through the design of a very simple class in Java. Here's the class:

class LogFacility
public log(final String message)
// implementation
LogFacility provides a mechanism to log messages. Everyone on the team would use this functionality as follows:
LogFacility lf = new LogFacility()
lf.log("log this message for me");

As it's simple and useful, it's hard to argue against it. Now I take this utility and ship it to two different teams. One team wants to log to a file and the other to stdout. I improvised and came up with StdoutLogFacility and FileLogFacility, and suggested that the programmer use the appropriate logging facility as follows:

StdoutLogFacility lf = new
lf.log("log this message for me");

FileLogFacility lf = new
lf.log("log this message for me");
You'd quickly realize that irrespective of what log facility is constructed, it gets used the same way. This is a cue to design an interface for the usage of the log facility as follows:
public interface ILogFacility { public
log(final String message); }
StdoutLogFacility and FileLogFacility would implement this interface. In this scenario the programmer would do the following:
ILogFacility lf = new
lf.log("log this message for me");
ILogFacility lf = new FileLogFacility();
lf.log("log this message for me");
As you can see, irrespective of the nature of the construction, an object of type ILogFacility is used the same way.

This brings us to an important observation in OO programming - construction is different from usage. In other words, the construction interface of an object is different from its usage contract/interface. We can delegate the construction of the ILogFacility to any number of mechanisms, but the usage remains the same. Using this property let's investigate a method where the programmer doesn't have to do the following:

ILogFacility lf = new FileLogFacility();
This line of code is hard-coding the construction of an implementation. In doing so we create a compile-time dependency with the implementation. And we can't substitute StdoutLogFacility for FileLogFacility because that dependency is necessitated by the compiling.

So, in a general sense, you can't really vary the implementation of a given interface at runtime if we use the "new" option for construction. Also you'll have to know the name of the implementation class, which may not even exist at compile time. What to do? The solution lies in understanding the factory pattern. Here's an example:

class ObjectFactory
public static Object create(final String
objectName, Object args )
throws CreationException;

You can attempt the following:

ILogFacility lf = ObjectFactory.create
(ILogFacility.NAME, null);
if.log("log my message"):
As a programmer you've delegated the construction of an interface named ILogFacility.NAME to a factory. This factory could look up a system-wide properties file for a class that's responsible for this interface and load it at runtime. Let's look at one such properties-file entry:

Assuming ILogFacility.NAME is "Objects.loggingObject", it is not difficult for the factory to do the following:

public static Object create(final String
objectName, Object args )
Properties systemWidePropertiesFile;
String className = systemWide
Object o = Class.forName(className);
return o;

Using this mechanism you can improvise StdoutLogFacility gradually without impacting its users. For example, you've improved logging but don't want to replace the older implementation until it's been field tested. You can cut and paste the source code of StdoutLogFacility to another class called StdoutLogFacility1 and replace your properties file as follows:

This way the older clients can continue to use the older implementation while you migrate to the new one. You can continue to evolve this functionality while incrementing the numbers. The same facility can provide a radically different implementation if necessary. For example:

logs all your messages to a socket.

This discussion isn't limited to logging; any of your core modules can follow the same pattern, which allows them a path for evolution while maintaining backward compatibility.

To summarize the points so far, we've learned the following:

  1. Construction is different from usage
  2. Use interfaces, not implementations for, key areas of functionality
  3. Use factories to construct implementations, at runtime
  4. You can use properties files to associate implementations with their interface names
  5. Having an interface.NAME as a standard allows a programmer a simple reference to instantiate an interface

Usage Pattern for an Evolving Implementation
Let's reexamine how we can utilize an interface. The emphasis here is that you get your implementations via a global factory instead of "new"ing them explicitly. This allows for runtime variations of the implementation. For example:

MyInterface i = (MyInterface)ObjectFactory.create
Let's examine the MyInterface.NAME:
interface MyInterface
public static final String NAME =
                                                                                                                        . .. other public method signatures
Using a synonym like "interface.NAME" instead of a literal string, we reduce the risk of getting the name wrong. If every interface has the same public synonym, it's just that much easier for the programmer to instantiate an implementation for it.

Interface Definition for an Application-Wide Factory Service
Now we'll discuss the factory object in more detail and define some desirable characteristics. The idea is we'll use this factory object to create all our implementations for the desired interfaces. By that I mean to choose interfaces that are going to be instantiated by factories. Once decided, these interfaces can be instantiated by the same global object factory. The aim of this section is to define a simple interface for such an application-wide factory service.

Static vs Nonstatic Method
The method "create" of the ObjectFactory is declared static and public. It's public for obvious reasons and static so the programmer can invoke it without an object reference. For example:

instead of
ObjectFactory of = new ObjectFactory();
There are some exceptions to this rule for example, if you want to evolve the functionality of the factory itself. The method also throws a suitable exception indicating any failures in the construction process. There are some interesting consequences to the nature of this exception, which I'll cover at the end of this article.

getObject vs createObject
At this point I'd like to change the name of the "create" method of the ObjectFactory to "getObject". create() implies that an object is being created every time the method is called. This may not be true for a number of reasons. Certain objects you may want to create only once, others with each request, and some as part of a pool. Because of this, getObject() suits the semantics of this intention more accurately.

Passing Arguments
Certain objects require construction arguments. How do you pass them? The arguments are passed via the second parameter to the function call. This could be any object, including a collection of objects that get passed to the constructor of the target object. This can get sophisticated with EJBs when the constructors are invoked through reflection and the correct constructor called. But for simplicity the classes can have default constructors, with a well-known "init()" method that accepts the passed parameter as an argument.

The implication is that programmers not only need to know the interface name of the object that they want to instantiate, but also the nature of its arguments. This I call the construction interface of the object. This needs to be published and adhered to by all the implementations. And it's the responsibility of the programmer to pass the correct set of arguments. Otherwise an exception is thrown by the generic factory.

Caching Strategy
Once you start using this facility, it won't be long before you start asking, "How can I limit the number of object occurrences of a specific class?" For example, singleton. To facilitate this a factory can use multiple strategies to cache object instances. The factory can save the instantiated objects in a hashtable keyed by their interface names. So, when a repeated request comes in for an interface, the factory can return the previously constructed object. But how does the factory know to cache an object? You can specify in the properties file that a certain interface needs to be cached, which is how it's done in EJBs at deployment time. Specifying the number of object instances at deployment time is more generic. But for systems of medium complexity, you may want to define an ISingleThreaded interface and implement that interface to force multiple instances of the object. This avoids the errors that might occur due to lack of knowledge at deployment time, or you could provide both facilities.

Name-Based Caching May Not Be Sufficient
Interface name-based caching sounds good until you consider the fact that a given implementation can support multiple interfaces. In this case you'll have two such objects cached when one would have been sufficient and even wrong at times. I believe the right approach is to use caching based on class names instead.

Pooling Support
I think a factory shouldn't provide pooling; it should be implemented on top of factory. Otherwise the simple factory interface also needs to deal with synchronization and return to pool semantics.

Support for Object Filters
When a factory instantiates an object, it can also pass the object to an object filter and return the output of the filter instead. This allows for the chaining of objects, which is similar to the servlet chaining popular in Web-based systems. It's fairly trivial to do, but adds a great value to the overall functionality. For example, using such a functionality you can convert an incoming result set to a comma-separated string or sum the values into a single entity. All this can be done without recompiling the target code. This properties file demonstrates how this can be accomplished:

The Default Object
When you're specifying target implementation objects via a properties file, it's possible that anything might go wrong in the construction process, resulting in an exception. In this case you'd like a default implementation to be available. For example:
MyInterface myObj = null;
myObj = ObjectFactory.getObject
catch( FactoryException x)
myObj = new MyDefaultObject;
Doing this everywhere discourages the programmer from using the facility. The following code alleviates the problem:
MyInterface myObj = ObjectFactory.get
Object (MyInterface.NAME, args, new
This method doesn't throw any exceptions, instead it returns the MyDefaultObject on any kind of internal exception, ensuring the default functionality of the application.

A Well-Defined Factory Interface to
Fulfill the Factory Service

With that discussion we're able to define an interface for our factory object:

interface IFactory
Object getObject(final String
interfaceName, Object args) throws
Object getObject(final String
interfaceName, Object args, Object
An interface definition tells you only the contract of the factory and doesn't specify its intended behavior. For that reason I'm summarizing here the desired characteristics of a typical factory implementation:
  1. Provides a static façade for easier calling semantics
  2. Uses getObject, not createObject, semantics
  3. Requires a default constructor for the objects to be constructed
  4. Arguments are passed to the init method for initialization
  5. Caching is based on the class name of the object
  6. Caching is also based on the IsingleThreaded tagging interface
  7. Supports object filters
  8. Supports default objects
  9. Uses an application-wide configuration interface for class definitions
ObjectFactory Implementation
Although we've defined an interface for a factory, we need a convenient set of static methods that would make use of the above interface internally. Such a facility provides the best of both worlds. On one side it obviates the need to instantiate a factory interface and on the other it adheres to a nonstatic factory interface definition. Here's one such implementation. Obviously many variations are possible, but the idea is to give the programmer the simplest way to accomplish the characteristics stated above (see Listing 1).

Role of an Application-Wide Configuration Service
So far all the object definitions are stored in a properties file. It's not that difficult for the factory implementation to instantiate a properties object and read in the properties file. What if in the future you'd like to move the entries from a properties file to a database, an LDAP, or an XML configuration file?

For this reason the factory implementation accesses the object definitions through a common configuration interface.

Interface Iconfig
public String getValue(final String key)
throws ConfigException;
public String getValue(final String key,
String defaultValue );
Again, for programmer simplicity, this interface is exposed through a static Config class as follows:
Class Config
static public String getValue(final String
key) throws ConfigException;
static public String getValue(final String
key, String defaultValue );
With this you'd be able to do:
String value = Config.getValue("key","default value");
Why go to such lengths when properties is such a simple interface; why not use it? Frequently you would want the IConfig implementation to exhibit the following characteristics:
  1. Case-insensitive keys so you don't have to constantly remember capitalizations
  2. Ability to include multiple-properties file inside the main configuration file
  3. Ability to provide substitutions based on keys that were defined at the beginning of the properties file
All these can be provided gradually by the evolving implementations of IConfig. In this case, one of the facilities of the framework evolves using the same principles.

Evolving an Interface
So far I've discussed where the implementations are changing. What if the interface itself has migrated to the next level? Although less common, this will happen eventually, even in the best of designed interfaces. For instance, with the logging interface defined above, I'd like to extend the interface by providing a logging mechanism for exceptions. One approach is to extend the base interface instead of modifying it:

interface ILogFacility_1 extends
public void log(Throwable t);
If there's an implementation that supports the ILogFacility_1 interface, it automatically supports the ILogInterface and hence can be used in a backward-compatible manner. On the other hand, if an older implementation that supports only ILogInterface is used in a newer environment that's expecting ILogFacility_1, there are two alternatives:
  1. Let the system throw a class-cast exception and correct the mistake
  2. Write the client code in such a way that this can be handled gracefully:
Object logFacility =
(ILogFacility.NAME,null,new MyLogFacility);
if (logFacility instanceof ILogFacility_1)
else (logFacility instanceof ILogFacility)
Request-Based Factories
As I've mentioned, factory plays a central role in adapting this evolution-based approach to programming. The factory I've discussed so far is primarily creation-based because it instantiates the necessary class and calls the well-known method to initialize it. A more sophisticated approach would be a request-based factory in which the input symbolic name refers to a request rather than a class name. You can simulate the creation-based factory from a request-based factory. For example:
Object o = RequestBasedFactory.getObject
("GET_OBJECT", null):
The request-based factory locates a class name identified by "GET_OBJECT" in a properties file. Instead of calling the init method to initialize the object, the request factory calls the "executeRequest" method with the parameters. Whatever the executeRequest method returns is then returned to the caller as the return object.

When the executeRequest method returns the self-reference, we basically have the RequestFactory behaving like a creation factory. RequestFactory has broader applications than a simple CreationFactory. For example:

ROWS","employee_name=John Doe")
invokes a database request executor identified by "GET_EMPLOYEE_ROWS" and returns the result set back to the caller.

Interfaces and Exceptions
I'd like to cover one more detail since we're dealing extensively with interfaces, particularly such generic interfaces as the factory interface I've shown here. When a factory tries to load a class at runtime and fails, all the client sees is the factory exception. If you're not careful, the root cause of the exception is never known. To deal with this scenario, interfaces should define exceptions that can carry with them a child exception, and the child exception can carry another child exception. This way the root exceptions are propagated all the way to the top. When the final exception is printed, you'll see a complete hierarchy of exceptions, which is extremely good for debugging purposes. I call this the principle of Kangaroo exceptions, and it's necessary for interface-based programming. This is because interfaces are like firewalls and compile-time exceptions can't propagate through them without help. This concept of Kangaroo exceptions hides the root exception in terms of the interface-specific exception.

Using a simple application-level factory service, it's possible to effectively employ interfaces and implementations to write code that provides backward compatibility. Even when you don't need this compatibility, it enables you to try new bug fixes without affecting the old behavior. This provides developers with some assurance that they won't undo everything they've done before.

More Stories By Satya Komatenini

Satya Komatineni is Chief Technology Officer of INDENT, Inc and the author of a Java based RAD framework for developing J2EE based HTML applications. The product has the distinction of supporting multiple html transformations (XSL,JSP, proprietary templates) while utilizing the same data abstraction to interact with EJBs, relational databases and ERP systems. After earning an M.S. in Electrical Engineering from Indian Institute of Technology, New Delhi, worked with LAN based collaboration technologies, C++ patterns and frameworks, Java and Web based frameworks in a distributed environment.

Comments (0)

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
Why do your mobile transformations need to happen today? Mobile is the strategy that enterprise transformation centers on to drive customer engagement. In his general session at @ThingsExpo, Roger Woods, Director, Mobile Product & Strategy – Adobe Marketing Cloud, covered key IoT and mobile trends that are forcing mobile transformation, key components of a solid mobile strategy and explored how brands are effectively driving mobile change throughout the enterprise.
SYS-CON Events announced today that ReadyTalk, a leading provider of online conferencing and webinar services, has been named Vendor Presentation Sponsor at the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. ReadyTalk delivers audio and web conferencing services that inspire collaboration and enable the Future of Work for today’s increasingly digital and mobile workforce. By combining intuitive, innovative tec...
If you’re responsible for an application that depends on the data or functionality of various IoT endpoints – either sensors or devices – your brand reputation depends on the security, reliability, and compliance of its many integrated parts. If your application fails to deliver the expected business results, your customers and partners won't care if that failure stems from the code you developed or from a component that you integrated. What can you do to ensure that the endpoints work as expect...
WebRTC adoption has generated a wave of creative uses of communications and collaboration through websites, sales apps, customer care and business applications. As WebRTC has become more mainstream it has evolved to use cases beyond the original peer-to-peer case, which has led to a repeating requirement for interoperability with existing infrastructures. In his session at @ThingsExpo, Graham Holt, Executive Vice President of Daitan Group, will cover implementation examples that have enabled ea...
There is growing need for data-driven applications and the need for digital platforms to build these apps. In his session at 19th Cloud Expo, Muddu Sudhakar, VP and GM of Security & IoT at Splunk, will cover different PaaS solutions and Big Data platforms that are available to build applications. In addition, AI and machine learning are creating new requirements that developers need in the building of next-gen apps. The next-generation digital platforms have some of the past platform needs a...
So, you bought into the current machine learning craze and went on to collect millions/billions of records from this promising new data source. Now, what do you do with them? Too often, the abundance of data quickly turns into an abundance of problems. How do you extract that "magic essence" from your data without falling into the common pitfalls? In her session at @ThingsExpo, Natalia Ponomareva, Software Engineer at Google, provided tips on how to be successful in large scale machine learning...
In his session at @ThingsExpo, Kausik Sridharabalan, founder and CTO of Pulzze Systems, Inc., will focus on key challenges in building an Internet of Things solution infrastructure. He will shed light on efficient ways of defining interactions within IoT solutions, leading to cost and time reduction. He will also introduce ways to handle data and how one can develop IoT solutions that are lean, flexible and configurable, thus making IoT infrastructure agile and scalable.
SYS-CON Events announced today that Numerex Corp, a leading provider of managed enterprise solutions enabling the Internet of Things (IoT), will exhibit at the 19th International Cloud Expo | @ThingsExpo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Numerex Corp. (NASDAQ:NMRX) is a leading provider of managed enterprise solutions enabling the Internet of Things (IoT). The Company's solutions produce new revenue streams or create operating...
In his general session at 18th Cloud Expo, Lee Atchison, Principal Cloud Architect and Advocate at New Relic, discussed cloud as a ‘better data center’ and how it adds new capacity (faster) and improves application availability (redundancy). The cloud is a ‘Dynamic Tool for Dynamic Apps’ and resource allocation is an integral part of your application architecture, so use only the resources you need and allocate /de-allocate resources on the fly.
IoT is fundamentally transforming the auto industry, turning the vehicle into a hub for connected services, including safety, infotainment and usage-based insurance. Auto manufacturers – and businesses across all verticals – have built an entire ecosystem around the Connected Car, creating new customer touch points and revenue streams. In his session at @ThingsExpo, Macario Namie, Head of IoT Strategy at Cisco Jasper, will share real-world examples of how IoT transforms the car from a static p...
Fifty billion connected devices and still no winning protocols standards. HTTP, WebSockets, MQTT, and CoAP seem to be leading in the IoT protocol race at the moment but many more protocols are getting introduced on a regular basis. Each protocol has its pros and cons depending on the nature of the communications. Does there really need to be only one protocol to rule them all? Of course not. In his session at @ThingsExpo, Chris Matthieu, co-founder and CTO of Octoblu, walk you through how Oct...
Web Real-Time Communication APIs have quickly revolutionized what browsers are capable of. In addition to video and audio streams, we can now bi-directionally send arbitrary data over WebRTC's PeerConnection Data Channels. With the advent of Progressive Web Apps and new hardware APIs such as WebBluetooh and WebUSB, we can finally enable users to stitch together the Internet of Things directly from their browsers while communicating privately and securely in a decentralized way.
"My role is working with customers, helping them go through this digital transformation. I spend a lot of time talking to banks, big industries, manufacturers working through how they are integrating and transforming their IT platforms and moving them forward," explained William Morrish, General Manager Product Sales at Interoute, in this SYS-CON.tv interview at 18th Cloud Expo, held June 7-9, 2016, at the Javits Center in New York City, NY.
The Internet of Things can drive efficiency for airlines and airports. In their session at @ThingsExpo, Shyam Varan Nath, Principal Architect with GE, and Sudip Majumder, senior director of development at Oracle, will discuss the technical details of the connected airline baggage and related social media solutions. These IoT applications will enhance travelers' journey experience and drive efficiency for the airlines and the airports. The session will include a working demo and a technical d...
Developing software for the Internet of Things (IoT) comes with its own set of challenges. Security, privacy, and unified standards are a few key issues. In addition, each IoT product is comprised of (at least) three separate application components: the software embedded in the device, the back-end service, and the mobile application for the end user’s controls. Each component is developed by a different team, using different technologies and practices, and deployed to a different stack/target –...
Identity is in everything and customers are looking to their providers to ensure the security of their identities, transactions and data. With the increased reliance on cloud-based services, service providers must build security and trust into their offerings, adding value to customers and improving the user experience. Making identity, security and privacy easy for customers provides a unique advantage over the competition.
SYS-CON Events announced today that Commvault, a global leader in enterprise data protection and information management, has been named “Bronze Sponsor” of SYS-CON's 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Commvault is a leading provider of data protection and information management solutions, helping companies worldwide activate their data to drive more value and business insight and to transform moder...
SYS-CON Events has announced today that Roger Strukhoff has been named conference chair of Cloud Expo and @ThingsExpo 2016 Silicon Valley. The 19th Cloud Expo and 6th @ThingsExpo will take place on November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. "The Internet of Things brings trillions of dollars of opportunity to developers and enterprise IT, no matter how you measure it," stated Roger Strukhoff. "More importantly, it leverages the power of devices and the Interne...
Personalization has long been the holy grail of marketing. Simply stated, communicate the most relevant offer to the right person and you will increase sales. To achieve this, you must understand the individual. Consequently, digital marketers developed many ways to gather and leverage customer information to deliver targeted experiences. In his session at @ThingsExpo, Lou Casal, Founder and Principal Consultant at Practicala, discussed how the Internet of Things (IoT) has accelerated our abil...
Digital innovation is the next big wave of business transformation based on digital technologies of which IoT and Big Data are key components, For example: Business boundary innovation is a challenge to excavate third-party business value using IoT and BigData, like Nest Business structure innovation may propose re-building business structure from scratch, as Uber does in the taxicab industry The social model innovation is also a big challenge to the new social architecture with the design fr...