Skip to content

Commit

Permalink
Adding composite specification (Issue#1093) (#1094)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
MaVdbussche authored and iluwatar committed Nov 17, 2019
1 parent 19b129c commit 73f9b8b
Show file tree
Hide file tree
Showing 20 changed files with 492 additions and 73 deletions.
98 changes: 81 additions & 17 deletions specification/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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();
Expand All @@ -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 {

Expand All @@ -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;

Expand All @@ -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;

Expand All @@ -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> redCreatures = creatures.stream().filter(new ColorSelector(Color.RED))
.collect(Collectors.toList());
```

But we could also use our parameterized selector like this :
```java
List<Creature> redAndFlyingCreatures = creatures.stream()
.filter(new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING))).collect(Collectors.toList());
List<Creature> heavyCreatures = creatures.stream().filter(new MassGreaterThanSelector(500.0)
.collect(Collectors.toList());
```

But we could also use our paramterized selector like this.
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
List<Creature> heavyCreatures = creatures.stream()
.filter(new MassGreaterThanSelector(500.0).collect(Collectors.toList());
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@
import com.iluwatar.specification.creature.Shark;
import com.iluwatar.specification.creature.Troll;
import com.iluwatar.specification.property.Color;
import com.iluwatar.specification.property.Mass;
import com.iluwatar.specification.property.Movement;
import com.iluwatar.specification.selector.AbstractSelector;
import com.iluwatar.specification.selector.ColorSelector;
import com.iluwatar.specification.selector.MassEqualSelector;
import com.iluwatar.specification.selector.MassGreaterThanSelector;
import com.iluwatar.specification.selector.MassSmallerThanOrEqSelector;
import com.iluwatar.specification.selector.MovementSelector;
Expand Down Expand Up @@ -77,13 +78,8 @@ public static void main(String[] args) {
List<Creature> darkCreatures =
creatures.stream().filter(new ColorSelector(Color.DARK)).collect(Collectors.toList());
darkCreatures.forEach(c -> LOGGER.info(c.toString()));
// find all red and flying creatures
LOGGER.info("Find all red and flying creatures");
List<Creature> redAndFlyingCreatures =
creatures.stream()
.filter(new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING)))
.collect(Collectors.toList());
redAndFlyingCreatures.forEach(c -> LOGGER.info(c.toString()));

LOGGER.info("\n");
// so-called "parameterized" specification
LOGGER.info("Demonstrating parameterized specification :");
// find all creatures heavier than 500kg
Expand All @@ -98,5 +94,26 @@ public static void main(String[] args) {
creatures.stream().filter(new MassSmallerThanOrEqSelector(500.0))
.collect(Collectors.toList());
lightCreatures.forEach(c -> LOGGER.info(c.toString()));

LOGGER.info("\n");
// so-called "composite" specification
LOGGER.info("Demonstrating composite specification :");
// find all red and flying creatures
LOGGER.info("Find all red and flying creatures");
List<Creature> redAndFlyingCreatures =
creatures.stream()
.filter(new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING)))
.collect(Collectors.toList());
redAndFlyingCreatures.forEach(c -> LOGGER.info(c.toString()));
// find all creatures dark or red, non-swimming, and heavier than or equal to 400kg
LOGGER.info("Find all scary creatures");
AbstractSelector<Creature> scaryCreaturesSelector = new ColorSelector(Color.DARK)
.or(new ColorSelector(Color.RED)).and(new MovementSelector(Movement.SWIMMING).not())
.and(new MassGreaterThanSelector(400.0).or(new MassEqualSelector(400.0)));
List<Creature> scaryCreatures =
creatures.stream()
.filter(scaryCreaturesSelector)
.collect(Collectors.toList());
scaryCreatures.forEach(c -> LOGGER.info(c.toString()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@

package com.iluwatar.specification.property;

/** Mass property. */
/**
* Mass property.
*/
public class Mass {

private double value;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

package com.iluwatar.specification.selector;

import java.util.function.Predicate;

/**
* Base class for selectors.
*/
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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,11 @@

import com.iluwatar.specification.creature.Creature;
import com.iluwatar.specification.property.Color;
import java.util.function.Predicate;

/**
* Color selector.
*/
public class ColorSelector implements Predicate<Creature> {
public class ColorSelector extends AbstractSelector<Creature> {

private final Color color;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

package com.iluwatar.specification.selector;

import java.util.List;

/**
* A Selector defined as the conjunction (AND) of other (leaf) selectors.
*/
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)));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

package com.iluwatar.specification.selector;

import java.util.List;

/**
* A Selector defined as the disjunction (OR) of other (leaf) selectors.
*/
public class DisjunctionSelector<T> extends AbstractSelector<T> {

private List<AbstractSelector<T>> leafComponents;

@SafeVarargs
DisjunctionSelector(AbstractSelector<T>... selectors) {
this.leafComponents = List.of(selectors);
}

/**
* Tests if *at least one* selector passes the test.
*/
@Override
public boolean test(T t) {
return leafComponents.stream().anyMatch(comp -> comp.test(t));
}
}

0 comments on commit 73f9b8b

Please sign in to comment.