Welcome!

Java IoT Authors: Liz McMillan, Elizabeth White, Yeshim Deniz, Zakia Bouachraoui, Pat Romanski

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.


IoT & Smart Cities Stories
The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
Machine learning has taken residence at our cities' cores and now we can finally have "smart cities." Cities are a collection of buildings made to provide the structure and safety necessary for people to function, create and survive. Buildings are a pool of ever-changing performance data from large automated systems such as heating and cooling to the people that live and work within them. Through machine learning, buildings can optimize performance, reduce costs, and improve occupant comfort by ...
The explosion of new web/cloud/IoT-based applications and the data they generate are transforming our world right before our eyes. In this rush to adopt these new technologies, organizations are often ignoring fundamental questions concerning who owns the data and failing to ask for permission to conduct invasive surveillance of their customers. Organizations that are not transparent about how their systems gather data telemetry without offering shared data ownership risk product rejection, regu...
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...