Tuesday, December 15, 2015

Thanks lambdas

With this post, I want to show you step by step the process of transforming a static and rigid code, to something more flexible and reusable using lambda expressions. Let's stop talking, let's to see code.

Imagine you have a selling car business, and you want an application to filtering the cars by brand. Then your business logic could look like this.


That it's ok. But now you want to filtering by brand and color too. You have to add a new method in order to support the new functionality. In this case, we can do it easily.


What can we say about this code? In front of any new requirement, a new method is implemented. Then we have the phenomenon of method explosion.

We can try to do it better with a new interface called CarChecker.

Yes, I know what are you thinking. Now we have a generic method, but now we have class explosion instead of method explosion. You are right. We can try to do it with anonymous classes.

But CarChecker it's a functional interface. We can use lambda expressions.


At this point, our code looks cool. But Java 8 includes something called Predicate. Then we can rewrite our business logic to this.

Usually, when you filter a collection of objects then you want to do something with the result. We can try to generalize a function to processing the result of cars filtering using Consumer interface, included also by Java 8.


And that's all. Code more flexible and reusable.

Thanks lambdas.

No comments:

Post a Comment