DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. JavaScript
  4. Streams vs. Decorators

Streams vs. Decorators

Here's one take on the problems with Java's Streams API and how decorators in your code can present a better OOP solution.

Yegor Bugayenko user avatar by
Yegor Bugayenko
·
Oct. 11, 17 · Tutorial
Like (32)
Save
Tweet
Share
26.77K Views

Join the DZone community and get the full member experience.

Join For Free

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.0 d || probe == 1.0 d) {
        continue;
    }
    if (++pos > 10) {
        break;
    }
    System.out.printf(
        "Probe #%d: %f", pos, probe * 100.0 d
    );
}


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.0 d || p == 1.0 d)
    .limit(10 L)
    .forEach(
        probe - > System.out.printf(
            "Probe #%d: %f", 0, probe * 100.0 d
        )
    );


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.0 d || probe == 1.0 d)
    .limit(10 L)
    .forEach(
        probe - > System.out.printf(
            "Probe #%d: %f",
            index.getAndIncrement(),
            probe * 100.0 d
        )
    );


"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.0 d || probe == 1.0 d
            ),
            10
        ),
        probe - > () - > {
            System.out.printf(
                "Probe #%d: %f", 0, probe * 100.0 d
            );
            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.0 d || probe == 1.0 d
            ),
            10
        ),
        probe - > index - > {
            System.out.printf(
                "Probe #%d: %f", index, probe * 100.0 d
            );
            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 that 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.0 d || probe == 1.0 d
    ),
    10
);
int pos = 0;
for (Double probe: probes) {
    System.out.printf(
        "Probe #%d: %f", pos++, probe * 100.0 d
    );
}


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

Stream (computing)

Published at DZone with permission of Yegor Bugayenko. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 7 Awesome Libraries for Java Unit and Integration Testing
  • Distributed SQL: An Alternative to Database Sharding
  • The Future of Cloud Engineering Evolves
  • Deploying Java Serverless Functions as AWS Lambda

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: