# Java 8: Composing functions using compose and andThen

#### In this article we will try the best two methods in The Java Functions Package .

#### So let’s explore the problem that we have already that these two methods solve with elegant way from my point of view.

### Consider this scenario :

You have a function that you want to apply on some arguments .. at that time the solution you came up with was perfect then some change arise and you have to add a new function to the old one so they made acompositefunction.

Now the solution may vary but in Java8+ the solution is so simple when consider using the new Functions Package which holds into it a lot of powerful Interfaces that you can use them and increase your productivity also the best usefulness is help you to apply the DRY principle.

What’s the Function class ? and What’s the beauty about it?

Function class represent the Function Terminology in Mathematica which is any formula that takes an argument and produce a value as result by processing that value.

In Java8+ Function class can reference any method that apply to that Terminology , So it’s the core of the functional programming capability .

let’s take a simple example :

### Let’s start composing more functions

#### Let’s create an example to see how we can use this approach to create small pieces of reusable code — then put them together in different ways.

### Consider the following.

We have a string that we need to toggle its case to be upper case then we need to trim the tailing and leading spaces.

Let’s start by introducing two basic functions —`upperCase`

and`trim`

- that do the two functionalities that we need.

**This powerfulness can lead to an amazing decoupled application that consist only from functions**

Not only the Function Class has these composition methods all the functional interfaces in the new Function Package also had a similar methods .

Now Lets see an example about using the compose function :

Whats the difference between andThen and composite ?

as we can see the execution order is the difference .

### Conclusion :

You should consider using the Functions Package Classes as your dependencies in your future work to decouple your modules and to have a freedom when changing and maintaining your code .