Java Reference
In-Depth Information
This is quite a neat way to make use of the Java 8 feature to achieve the same intent as the
factory pattern. But this technique doesn't scale very well if the factory method createProduct
needs to take multiple arguments to pass on to the product constructors! You'd have to provide
a different functional interface than a simple Supplier.
For example, suppose you want to store constructors for products that take three arguments
(two Integers and a String); you'd need to create a special functional interface TriFunction to
support this. As a result, the signature of the Map becomes more complex:
public interface TriFunction<T, U, V, R>{
R apply(T t, U u, V v);
}
Map<String, TriFunction<Integer, Integer, String, Product>> map
= new HashMap<>();
You've seen how to write and refactor code using lambda expressions. You'll now see how you
can ensure your new code is correct.
8.3. Testing lambdas
You've now sprinkled your code with lambda expressions, and it looks nice and concise. But in
most developer jobs you're not paid for writing nice code but for writing code that's correct.
Generally, good software engineering practice involves using unit testing to ensure that your
program behaves as intended. You write test cases, which assert that small individual parts of
your source code are producing the expected results. For example, consider a simple Point class
for a graphical application:
public class Point{
private final int x;
private final int y;
private Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
 
Search WWH ::




Custom Search