Adding composite specification (Issue#1093) (#1094)

* Resolution proposition to Issue#1055 (UML diagram left to do)

* Deciding not to modify the UML diagram for now

* Resolution proposition to Issue#1093

* Code reformatting
This commit is contained in:
Martin Vandenbussche
2019-11-17 13:25:32 +01:00
committed by Ilkka Seppälä
parent 19b129c28e
commit 73f9b8bef1
20 changed files with 494 additions and 75 deletions

View File

@ -31,7 +31,8 @@ Use the Specification pattern when
Real world example
> There is a pool of different creatures and we often need to select some subset of them. We can write our search specification such as "creatures that can fly" or "creatures heavier than 500 kilograms" and give it to the party that will perform the filtering.
> There is a pool of different creatures and we often need to select some subset of them.
> We can write our search specification such as "creatures that can fly", "creatures heavier than 500 kilograms", or as a combination of other search specifications, and then give it to the party that will perform the filtering.
In Plain Words
@ -44,8 +45,10 @@ Wikipedia says
**Programmatic Example**
If we look at our creature pool example from above, we have a set of creatures with certain properties.\
Those properties can be part of a pre-defined, limited set (represented here by the enums Size, Movement and Color); but they can also be discrete (e.g. the mass of a Creature). In this case, it is more appropriate to use what we call "parameterized specification", where the property value can be given as an argument when the Creature is created, allowing for more flexibility.
Those properties can be part of a pre-defined, limited set (represented here by the enums Size, Movement and Color); but they can also be continuous values (e.g. the mass of a Creature).
In this case, it is more appropriate to use what we call "parameterized specification", where the property value can be given as an argument when the Creature is instantiated, allowing for more flexibility.
A third option is to combine pre-defined and/or parameterized properties using boolean logic, allowing for near-endless selection possibilities (this is called Composite Specification, see below).
The pros and cons of each approach are detailed in the table at the end of this document.
```java
public interface Creature {
String getName();
@ -56,8 +59,7 @@ public interface Creature {
}
```
And dragon implementation looks like this.
And ``Dragon`` implementation looks like this.
```java
public class Dragon extends AbstractCreature {
@ -67,10 +69,9 @@ public class Dragon extends AbstractCreature {
}
```
Now that we want to select some subset of them, we use selectors. To select creatures that fly, we should use MovementSelector.
Now that we want to select some subset of them, we use selectors. To select creatures that fly, we should use ``MovementSelector``.
```java
public class MovementSelector implements Predicate<Creature> {
public class MovementSelector extends AbstractSelector<Creature> {
private final Movement movement;
@ -85,10 +86,9 @@ public class MovementSelector implements Predicate<Creature> {
}
```
On the other hand, we selecting creatures heavier than a chosen amount, we use MassGreaterThanSelector.
On the other hand, when selecting creatures heavier than a chosen amount, we use ``MassGreaterThanSelector``.
```java
public class MassGreaterThanSelector implements Predicate<Creature> {
public class MassGreaterThanSelector extends AbstractSelector<Creature> {
private final Mass mass;
@ -103,20 +103,84 @@ public class MassGreaterThanSelector implements Predicate<Creature> {
}
```
With these building blocks in place, we can perform a search for red and flying creatures like this.
With these building blocks in place, we can perform a search for red creatures as follows :
```java
List<Creature> redAndFlyingCreatures = creatures.stream()
.filter(new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING))).collect(Collectors.toList());
List<Creature> redCreatures = creatures.stream().filter(new ColorSelector(Color.RED))
.collect(Collectors.toList());
```
But we could also use our paramterized selector like this.
But we could also use our parameterized selector like this :
```java
List<Creature> heavyCreatures = creatures.stream()
.filter(new MassGreaterThanSelector(500.0).collect(Collectors.toList());
List<Creature> heavyCreatures = creatures.stream().filter(new MassGreaterThanSelector(500.0)
.collect(Collectors.toList());
```
Our third option is to combine multiple selectors together. Performing a search for special creatures (defined as red, flying, and not small) could be done as follows :
```java
AbstractSelector specialCreaturesSelector =
new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING)).and(new SizeSelector(Size.SMALL).not());
List<Creature> specialCreatures = creatures.stream().filter(specialCreaturesSelector)
.collect(Collectors.toList());
```
**More on Composite Specification**
In Composite Specification, we will create custom instances of ``AbstractSelector`` by combining other selectors (called "leaves") using the three basic logical operators.
These are implemented in ``ConjunctionSelector``, ``DisjunctionSelector`` and ``NegationSelector``.
```java
public abstract class AbstractSelector<T> implements Predicate<T> {
public AbstractSelector<T> and(AbstractSelector<T> other) {
return new ConjunctionSelector<>(this, other);
}
public AbstractSelector<T> or(AbstractSelector<T> other) {
return new DisjunctionSelector<>(this, other);
}
public AbstractSelector<T> not() {
return new NegationSelector<>(this);
}
}
```
```java
public class ConjunctionSelector<T> extends AbstractSelector<T> {
private List<AbstractSelector<T>> leafComponents;
@SafeVarargs
ConjunctionSelector(AbstractSelector<T>... selectors) {
this.leafComponents = List.of(selectors);
}
/**
* Tests if *all* selectors pass the test.
*/
@Override
public boolean test(T t) {
return leafComponents.stream().allMatch(comp -> (comp.test(t)));
}
}
```
All that is left to do is now to create leaf selectors (be it hard-coded or parameterized ones) that are as generic as possible,
and we will be able to instantiate the ``AbstractSelector`` class by combining any amount of selectors, as exemplified above.
We should be careful though, as it is easy to make a mistake when combining many logical operators; in particular, we should pay attention to the priority of the operations.\
In general, Composite Specification is a great way to write more reusable code, as there is no need to create a Selector class for each filtering operation.
Instead, we just create an instance of ``AbstractSelector`` "on the spot", using tour generic "leaf" selectors and some basic boolean logic.
**Comparison of the different approaches**
| Pattern | Usage | Pros | Cons |
|---|---|---|---|
| Hard-Coded Specification | Selection criteria are few and known in advance | + Easy to implement | - Inflexible |
| | | + Expressive |
| Parameterized Specification | Selection criteria are a large range of values (e.g. mass, speed,...) | + Some flexibility | - Still requires special-purpose classes |
| Composite Specification | There are a lot of selection criteria that can be combined in multiple ways, hence it is not feasible to create a class for each selector | + Very flexible, without requiring many specialized classes | - Somewhat more difficult to comprehend |
| | | + Supports logical operations | - You still need to create the base classes used as leaves |
## Related patterns
* Repository