Core Java

Streams vs. Decorators

The Streams API was introduced in Java 8, together with lambda expressions, just a few years ago. I, as a disciplined Java adept, tried to use this new feature in a few of my projects, for example here and here. I didn’t really like it and went back to good old decorators. Moreover, I created Cactoos, a library of decorators, to replace Guava, which is not so good in so many places.

Here is a primitive example. Let’s say we have a collection of measurements coming in from some data source, they are all numbers between zero and one:

Iterable<Double> probes;

Now, we need to show only the first 10 of them, ignoring zeros and ones, and re-scaling them to (0..100). Sounds like an easy task, right? There are three ways to do it: procedural, object-oriented, and the Java 8 way. Let’s start with the procedural way:

int pos = 0;
for (Double probe : probes) {
  if (probe == 0.0d || probe == 1.0d) {
    continue;
  }
  if (++pos > 10) {
    break;
  }
  System.out.printf(
    "Probe #%d: %f", pos, probe * 100.0d
  );
}

Why is this a procedural way? Because it’s imperative. Why is it imperative? Because it’s procedural. Nah, I’m kidding.

It’s imperative because we’re giving instructions to the computer about what data to put where and how to iterate through it. We’re not declaring the result, but imperatively building it. It works, but it’s not really scalable. We can’t take part of this algorithm and apply it to another use case. We can’t really modify it easily, for example to take numbers from two sources instead of one, etc. It’s procedural. Enough said. Don’t do it this way.

Now, Java 8 gives us the Streams API, which is supposed to offer a functional way to do the same. Let’s try to use it.

First, we need to create an instance of Stream, which Iterable doesn’t let us obtain directly. Then we use the stream API to do the job:

StreamSupport.stream(probes.spliterator(), false)
  .filter(p -> p == 0.0d || p == 1.0d)
  .limit(10L)
  .forEach(
    probe -> System.out.printf(
      "Probe #%d: %f", 0, probe * 100.0d
    )
  );

This will work, but will say Probe #0 for all probes, because forEach() doesn’t work with indexes. There is no such thing as forEachWithIndex() in the Stream interface as of Java 8 (and Java 9 too). Here is a workaround with an atomic counter:

AtomicInteger index = new AtomicInteger();
StreamSupport.stream(probes.spliterator(), false)
  .filter(probe -> probe == 0.0d || probe == 1.0d)
  .limit(10L)
  .forEach(
    probe -> System.out.printf(
      "Probe #%d: %f",
      index.getAndIncrement(),
      probe * 100.0d
    )
  );

“What’s wrong with that?” you may ask. First, see how easily we got into trouble when we didn’t find the right method in the Stream interface. We immediately fell off the “streaming” paradigm and got back to the good old procedural global variable (the counter). Second, we don’t really see what’s going on inside those filter(), limit(), and forEach() methods. How exactly do they work? The documentation says that this approach is “declarative” and each method in the Stream interface returns an instance of some class. What classes are they? We have no idea by just looking at this code.

The biggest issue with this streaming API is the very interface Stream, it’s huge!

These two problems are connected. The biggest issue with this streaming API is the very interface Stream—it’s huge. At the time of writing there are 43 methods. Forty three, in a single interface! This is against each and every principle of object-oriented programming, starting with SOLID and then up to more serious ones.

What is the object-oriented way to implement the same algorithm? Here is how I would do it with Cactoos, which is just a collection of primitive simple Java classes:

new And(
  new Mapped<Double, Scalar<Boolean>>(
    new Limited<Double>(
      new Filtered<Double>(
        probes,
        probe -> probe == 0.0d || probe == 1.0d
      ),
      10
    ),
    probe -> () -> {
      System.out.printf(
        "Probe #%d: %f", 0, probe * 100.0d
      );
      return true;
    }
  ),
).value();

Let’s see what’s going on here. First, Filtered decorates our iterable probes to take certain items out of it. Notice that Filtered implements Iterable. Then Limited, also being an Iterable, takes only the first ten items out. Then Mapped converts each probe into an instance of Scalar<Boolean>, which does the line printing.

Finally, the instance of And goes through the list of “scalars” and ask each of them to return boolean. They print the line and return true. Since it’s true, And makes the next attempt with the next scalar. Finally, its method value() returns true.

But wait, there are no indexes. Let’s add them. In order to do that we just use another class, called AndWithIndex:

new AndWithIndex(
  new Mapped<Double, Func<Integer, Boolean>>(
    new Limited<Double>(
      new Filtered<Double>(
        probes,
        probe -> probe == 0.0d || probe == 1.0d
      ),
      10
    ),
    probe -> index -> {
      System.out.printf(
        "Probe #%d: %f", index, probe * 100.0d
      );
      return true;
    }
  ),
).value();

Instead of Scalar<Boolean> we now map our probes to Func<Integer, Boolean> to let them accept the index.

The beauty of this approach is that all classes and interfaces are small and that’s why they’re very composable. To make an iterable of probes limited we decorate it with Limited; to make it filtered we decorate it with Filtered; to do something else we create a new decorator and use it. We’re not stuck to one single interface like Stream.

The bottom line is that decorators are an object-oriented instrument to modify the behavior of collections, while streams is something else which I can’t even find the name for.

P.S. By the way, this is how the same algorithm can be implemented with the help of Guava’s Iterables:

Iterable<Double> ready = Iterables.limit(
  Iterables.filter(
    probes,
    probe -> probe == 0.0d || probe == 1.0d
  ),
  10
);
int pos = 0;
for (Double probe : probes) {
  System.out.printf(
    "Probe #%d: %f", pos++, probe * 100.0d
  );
}

This is some weird combination of object-oriented and functional styles.

Published on Java Code Geeks with permission by Yegor Bugayenko, partner at our JCG program. See the original article here: Streams vs. Decorators

Opinions expressed by Java Code Geeks contributors are their own.

Yegor Bugayenko

Yegor Bugayenko is an Oracle certified Java architect, CEO of Zerocracy, author of Elegant Objects book series about object-oriented programing, lead architect and founder of Cactoos, Takes, Rultor and Jcabi, and a big fan of test automation.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
John
John
6 years ago

One must also install Hamcrest. The Hamcrest download has a script that installs and uses Gradle to build. One can use any other method such as Ant or jmk.

Jarrod Roberson
Jarrod Roberson
6 years ago

I agree the streams interface is “magic” and in many cases just not performant. But I have to say your decorator solutions might be more “elegant” they are much more obfuscated, especially with the terrible formatting. The imperative solutions is the most popular one by far because it is more obvious what it is doing and thus more maintainable. Your decorator solution is more functional but only about half-way. Having all the decorators take multiple arguments is a strange mix of functional and object oriented. The same thing you claim about the Guava solution. Here is a more idiomatic solution… Read more »

Jarrod Roberson
Jarrod Roberson
6 years ago

Also your filter logic will not work, that is not how you compare Doubles.

It should read like:
final Double ZERO = 0.0d;
final Double ONE = 1.0d;

The you use the .compareTo because of rounding and inaccuracy issues inherent in working for floating point numbers.

probe -> ZERO.compareTo(probe) 0

Jarrod Roberson
Jarrod Roberson
6 years ago

It truncated the correct comparison code and I can not edit the comment.

filter(probes, probe -> ZERO.compareTo(probe) 0)

Jarrod Roberson
Jarrod Roberson
6 years ago

filter(probes, probe -> ZERO.compareTo(probe) \ 0)

if this is truncated as well because they are not escaping the less than sign, just see the code in the link above.

Back to top button