Welcome!

Java IoT Authors: Liz McMillan, Elizabeth White, Don MacVittie, Pat Romanski, Roger Strukhoff

Related Topics: Java IoT

Java IoT: Article

The Rise of Functional Java Programming

Better living without side effects

But in real-life object-oriented programming, subtle problems begin to emerge due to the too frequent use of mutable (i.e., changeable) state. Even this simple Reader example can be hard to understand if readers are shared or accessed concurrently from multiple threads. For example, what does the following code example do?

public static void main(String[] args) {

 Reader arrayReader = new ArrayReader (new String[] { “Foo”, “Bar”, “Baz” });
 Reader charReader = new CharReader (arrayReader);

 String s = arrayReader.read();
 while (s != null) {
  System.out.println (s);
  System.out.println (charReader.read());    // uh oh
  s = arrayReader.read();
 }
}

As it turns out, the result is:

Foo
B
Baz
a

The B and the a on the second and fourth line of the output come from the word “Bar.” It’s confusing because the loop alternates each call to arrayReader.read() that pops a word from the ArrayReader, with a call to charReader.read() that pops a word from the same ArrayReader every time it runs out of characters. The spirit of these classes was to call either the ArrayReader or the CharReader in a loop, but not to make calls to the same ArrayReader both directly and indirectly via the CharReader class. But nothing in the object-oriented paradigm (or any paradigm) stops people from violating unwritten rules. As a result, you have to understand exactly how the ArrayReader and CharReader objects interact to predict what will happen. The problem is magnified if your program is multithreaded.

The fundamental problem is that each object behaves differently depending on its current state. (Obviously the second time you call read() on an ArrayReader you get a different result from the first time you call it.) That means that in general, if you want to understand what any particular operation is doing to an object, you have to know exactly what state the object was in before you invoked the operation. But to know that you have to know at what point the object was created, and the exact sequence of subsequent operations that might have changed the object’s internal state. That’s easy if the object reference is assigned to only a local variable and never shared, but if the object reference can be obtained from anywhere in your application via reflection or a directory service, then all bets are off.

Adding Fuel to the Fire by Abstracting Away Object Creation
Design patterns that abstract away the process of object creation bring a huge amount of benefit in terms of software configuration management and testability. Such design patterns have become enormously popular in recent years, but they are problematic when combined with the use of mutable state. A programmer cannot determine which classes a particular code sequence will instantiate just by looking at the code, and therefore cannot reason about the code until the runtime behavior of the object factory is fully understood. For example, let’s say we decide to rewrite our example based on Spring retaining the exact same behavior as before:

public static void main(String[] args) {

 BeanFactory factory = new XmlBeanFactory(new FileSystemResource(“applicationContext.xml”));
 Reader arrayReader = (Reader) factory.getBean (“arrayReader”);
 Reader charReader = (Reader) factory.getBean (“charReader”);

 String s = arrayReader.read();
 while (s != null) {
  System.out.println (s);
  System.out.println (charReader.read());
  s = arrayReader.read();
 }
}

The underlying classes have not been changed at all, nor has the main logic, but we have left the instantiation of the classes to the Spring framework. Would you be able to understand the code sequence above if you hadn’t read the introduction to this article? For completeness, here is the applicationContext.xml file:

<beans>

 <bean id=”arrayReader” class=”ArrayReader”>
  <constructor-arg>
   <list>
        <value>Foo</value>
        <value>Bar</value>
        <value>Baz</value>
   </list>
  </constructor-arg>
 </bean>

 <bean id=”charReader” class=”CharReader”>
  <constructor-arg ref=”arrayReader” />
 </bean>

</beans>

Note that we used constructor-based dependency injection, but it’s common to use setter-based injection in which case we would have added setters to each class for the String array and Reader dependencies, thus creating even more mutable state. By changing this XML file we can cause our program to behave completely differently. Here is a version, for example, that provides the CharReader object with its own private ArrayReader and eliminates the confusing sharing of the mutable state:

<beans>

 <bean id=”arrayReader” class=”ArrayReader”>
  <constructor-arg>
   <list>
        <value>Foo</value>
        <value>Bar</value>
        <value>Baz</value>
   </list>
  </constructor-arg>
 </bean>

 <bean id=”charReader” class=”CharReader”>
  <constructor-arg>
   <bean class=”ArrayReader”>
    <constructor-arg>
     <list>
          <value>Hello</value>
     </list>
    </constructor-arg>
   </bean>
  </constructor-arg>
 </bean>

</beans>

This version produces the output:

Foo
H
Bar
e
Baz
l

With this change to the configuration file, the main loop prints Foo, Bar, and Baz as expected, and the CharReader prints out individual characters from the word Hello. They no longer interfere with each other. The question of whether or not the main ArrayReader’s state is shared (creating the undesired interaction between the classes) depends on the application configuration file, which illustrates why the configuration file must be read and understood to predict the behavior of the actual program. When we are talking about configuration files running to hundreds and thousands of lines of XML, this can be daunting.

This is not a straw man argument. Code like this is getting written and deployed every day in mission-critical enterprise applications. We’ve had to debug some of it. We are not saying that object-oriented programming is bad, or that it’s wrong to abstract away the process of object creation. On the contrary, our point is that mutable state makes programs hard to understand, and modern programming practices magnify the problem. Complexity in software is inescapable, but unnecessary complexity is, well, unnecessary. By attacking the problem at its root (mutable state), we hope to have our cake and eat it too.

Functional Programming: An Alternative Approach
To understand better how functional programming can simplify this problem, we’ll first look at an even simpler problem in Haskell (one of the most mature modern functional programming languages).

If you only remember one thing about functional programming, it should be this central idea: that it should be possible to substitute a function call with its result, without changing the meaning of a program. This simple principle (generally referred to as referential transparency) has radical implications. At its best, this idea strengthens the intuition we’ve developed from high school algebra that, difficult as a problem may be, we can write it out in its entirety and solve it by progressively simplifying it.

Rather than taking on the full-grown horror of a decades-old legacy system, let’s consider a very simple functional program and analyze it in ways representative of real-life concerns.

sum [] = 0
sum x:xs = x + sum xs

This definition is intended to describe a function, “sum,” that adds up all of the numbers in a list. If the input list is empty (denoted by empty square brackets) the sum is 0. Otherwise we can break the list into its head (“x”) and its tail (“xs” – read as the plural of “x”), in which case the sum is just the head plus the sum of the tail. It might help clarify this to read the function out loud in English:

“The sum of an empty list is zero. Otherwise, the list has an initial value x followed by the remaining values xs, and the sum is x plus the sum of the xs.”

This is a recursive definition, and although it may at first glance seem like an endless loop, the sum will always decrease the length of the input list by one until the simplest case (the empty list) is reached. Let’s try it out on an example:

sum [1, 2, 3, 4, 5]

More Stories By Joe Morrison

Joe Morrison is a managing consultant at Lab49, and has over 20 years of experience leading engineering teams in designing and building complex network-based applications. His projects have ranged from distributed object research at Verizon Laboratories, to value chain management software at Benchmarking Partners in Boston, to in-the-trenches SOA projects for financial services firms in New York. Joe holds a BMath degree in computer science from the University of Waterloo, and a master's degree in computer science from MIT. He is a regular blogger on http://blog.lab49.com/.

More Stories By Kalani Thielen

Kalani Thielen is a Lab49 technology consultant, working in the financial services industry. Prior to joining Lab49 in 2006, he worked for six years developing products for the publishing, advertising, and communications industries. As a specialist in programming language theory, his present work focuses on the development and certification of compilers for bond pricing and trading languages.

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
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
@DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...
SYS-CON Events announced today that Cedexis will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
SYS-CON Events announced today that Google Cloud has been named “Keynote Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.
SYS-CON Events announced today that Vivint to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. As a leading smart home technology provider, Vivint offers home security, energy management, home automation, local cloud storage, and high-speed Internet solutions to more than one million customers throughout the United States and Canada. The end result is a smart home solution that sav...
SYS-CON Events announced today that Opsani will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Opsani is the leading provider of deployment automation systems for running and scaling traditional enterprise applications on container infrastructure.
SYS-CON Events announced today that Nirmata will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nirmata provides a comprehensive platform, for deploying, operating, and optimizing containerized applications across clouds, powered by Kubernetes. Nirmata empowers enterprise DevOps teams by fully automating the complex operations and management of application containers and its underlying ...
SYS-CON Events announced today that Opsani to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. Opsani is creating the next generation of automated continuous deployment tools designed specifically for containers. How is continuous deployment different from continuous integration and continuous delivery? CI/CD tools provide build and test. Continuous Deployment is the means by which...