Skip to content

Commit acb2eae

Browse files
committed
docs: update function composition
1 parent ec5d08e commit acb2eae

File tree

1 file changed

+55
-35
lines changed

1 file changed

+55
-35
lines changed

function-composition/README.md

Lines changed: 55 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,83 @@
11
---
22
title: Function Composition
3-
category: Behavioral
3+
category: Functional
44
language: en
55
tag:
6-
- Functional Programming
7-
- Functional decomposition
8-
- Java
6+
- Code simplification
7+
- Composition
8+
- Decoupling
9+
- Functional decomposition
10+
- Lambda
11+
- Reusability
912
---
1013

1114
## Also known as
1215

13-
Functional Composition
16+
* Function Chaining
17+
* Function Pipelining
18+
* Functional Composition
1419

1520
## Intent
21+
1622
To enable creating complex functions by composing simpler ones, enhancing modularity and reusability of function-based logic.
1723

1824
## Explanation
1925

20-
Real-world example:
26+
Real-world example
2127

22-
> In financial software, functions that calculate various financial metrics can be composed to provide detailed analysis. For instance, a function that calculates interest can be composed with another that adjusts for taxes, allowing for a modular yet comprehensive financial assessment tool.
28+
> Imagine a fast-food restaurant where the process of making a burger is broken down into several steps: grilling the patty, toasting the bun, adding condiments, and assembling the burger. Each of these steps can be seen as a function.
29+
>
30+
> In the Functional Composition design pattern, these individual steps (functions) can be composed into a complete burger-making process. Each step remains simple and reusable. For instance, the grilling function could be reused for making sandwiches or other dishes that require a grilled patty. This modular approach allows the restaurant to efficiently create various menu items by reusing and combining simple, predefined steps.
2331
24-
In plain words:
32+
In plain words
2533

2634
> The Function Composer pattern allows building complex functions by combining simpler ones, making it easier to manage, test, and reuse individual pieces of functionality.
2735
28-
Wikipedia says:
36+
Wikipedia says
2937

3038
> Function composition is an act or mechanism to combine simple functions to build more complicated ones. Like the usual composition of functions in mathematics, the result of each function is passed as the argument of the next, and the result of the last one is the result of the whole.
3139
3240
**Programmatic Example**
3341

34-
Here is how the Function Composer pattern might be implemented and used in Java:
42+
Let's start with defining two simple functions. In this case, we have a function `timesTwo` that multiplies its input by 2, and a function `square` that squares its input.
3543

3644
```java
37-
public class FunctionComposer {
45+
Function<Integer, Integer> timesTwo = x -> x * 2;
46+
Function<Integer, Integer> square = x -> x * x;
47+
```
3848

39-
public static Function<Integer, Integer> composeFunctions(Function<Integer, Integer> f1, Function<Integer, Integer> f2) {
40-
return f1.andThen(f2);
41-
}
42-
}
49+
Next, we use the `FunctionComposer` class to compose these two functions into a new function. The `composeFunctions` method takes two functions as arguments and returns a new function that is the composition of the input functions.
50+
51+
```java
52+
Function<Integer, Integer> composedFunction = FunctionComposer.composeFunctions(timesTwo, square);
4353
```
54+
55+
Finally, we apply the composed function to an input value. In this case, we apply it to the number 3. The result is the square of the number 3 multiplied by 2, which is 36.
56+
4457
```java
45-
public class App {
46-
public static void main(String[] args) {
47-
Function<Integer, Integer> timesTwo = x -> x * 2;
48-
Function<Integer, Integer> square = x -> x * x;
58+
public static void main(String[] args) {
59+
final var logger = LoggerFactory.getLogger(App.class);
60+
Function<Integer, Integer> timesTwo = x -> x * 2;
61+
Function<Integer, Integer> square = x -> x * x;
4962

50-
Function<Integer, Integer> composedFunction = FunctionComposer.composeFunctions(timesTwo, square);
63+
Function<Integer, Integer> composedFunction = FunctionComposer.composeFunctions(timesTwo, square);
5164

52-
int result = composedFunction.apply(3);
53-
logger.info("Result of composing 'timesTwo' and 'square' functions applied to 3 is: " + result);
54-
}
65+
int result = composedFunction.apply(3);
66+
logger.info("Result of composing 'timesTwo' and 'square' functions applied to 3 is: " + result);
5567
}
5668
```
5769

58-
Result:
70+
This will output:
71+
5972
```
60-
Result of composing 'timesTwo' and 'square' functions applied to 3 is: 36 // Result will be 36 (3 * 2 = 6, 6 * 6 = 36)
73+
Result of composing 'timesTwo' and 'square' functions applied to 3 is: 36
6174
```
6275

63-
Use ``.compose()`` function when you need pre-compose and ``.andThen()`` function when you need post-compose.
76+
This example demonstrates how the Function Composition pattern can be used to create complex functions by composing simpler ones, enhancing modularity and reusability of function-based logic.
6477

6578
## Sequence diagram
6679

67-
![Functional Composer Diagram](./etc/function.composition.urm.png "function composition")
80+
![Functional Composition Diagram](./etc/function.composition.urm.png "Functional Composition")
6881

6982
## Applicability
7083

@@ -73,10 +86,13 @@ Use the Function Composer pattern when:
7386
* You want to create a pipeline of operations where the output of one function is the input to another.
7487
* You need to enhance the clarity and quality of your code by structuring complex function logic into simpler, reusable components.
7588
* You are working in a functional programming environment or a language that supports higher-order functions.
89+
* When you want to avoid deep nesting of function calls and instead build a pipeline of operations.
90+
* When aiming to promote immutability and side-effect-free functions in your design.
7691

7792
## Tutorials
7893

79-
[Function Composition in Java](https://functionalprogramming.medium.com/function-composition-in-java-beaf39426f52)
94+
* [Function Composition in Java (Medium)](https://functionalprogramming.medium.com/function-composition-in-java-beaf39426f52)
95+
* [Functional Programming in Java (Baeldung)](https://www.baeldung.com/java-functional-programming)
8096

8197
## Known uses
8298

@@ -91,19 +107,23 @@ Benefits:
91107
* High reusability of composed functions.
92108
* Increased modularity, making complex functions easier to understand and maintain.
93109
* Flexible and dynamic creation of function pipelines at runtime.
94-
*
95-
Drawbacks:
110+
* Enhances readability by structuring code in a linear, declarative manner.
111+
* Facilitates easier testing of individual functions.
112+
113+
Trade-offs:
96114

97115
* Potentially higher complexity when debugging composed functions.
98116
* Overhead from creating and managing multiple function objects in memory-intensive scenarios.
117+
* May require a paradigm shift for developers unfamiliar with functional programming concepts.
99118

100119
## Related patterns
101120

102-
* Chain of Responsibility
103-
* Decorator
104-
* Strategy
121+
* [Chain of Responsibility](https://java-design-patterns.com/patterns/chain-of-responsibility/) - Both patterns allow processing to be broken down into a series of steps, but Functional Composition focuses on function composition rather than responsibility delegation.
122+
* [Decorator](https://java-design-patterns.com/patterns/decorator/) - Similar in combining behaviors, but Decorator applies additional behavior to objects, while Functional Composition builds new functions.
123+
* [Strategy](https://java-design-patterns.com/patterns/strategy/) - Provides interchangeable functions (strategies), which can be composed in Functional Composition.
105124

106125
## Credits
107126

108-
[Functional Programming in Java](https://www.baeldung.com/java-functional-programming)
109-
[Function Composition in Java](https://functionalprogramming.medium.com/function-composition-in-java-beaf39426f52)
127+
* [Effective Java](https://amzn.to/4cGk2Jz)
128+
* [Functional Programming in Java](https://amzn.to/3JUIc5Q)
129+
* [Java 8 in Action: Lambdas, Streams, and functional-style programming](https://amzn.to/3QCmGXs)

0 commit comments

Comments
 (0)