- Functional Programming in Java venkat(9): Designing with Lambda Expressions part1
- Introduction
- Designing with Lambda Expressions
- Separating Concerns Using Lambda Expressions
- Exploring Design Concerns
- Getting Entangled with the Concerns
- Refactoring to Separate a Key Concern
- Delegating Using Lambda Expressions
- Creating a Delegate
- Stubbing the Web Service
- Integrating with the Web Service
- 其他
- 总结
- 参考
这里是记录学习这本书 Functional Programming in Java: Harnessing the Power Of Java 8 Lambda Expressions 的读书笔记,如有侵权,请联系删除。
About the author
Designing with Lambda ExpressionsVenkat Subramaniam
Dr. Venkat Subramaniam, founder of Agile Developer, Inc., has trained and mentored thousands of software developers in the US, Canada, Europe, and Asia. Venkat helps his clients effectively apply and succeed with agile practices on their software projects. He is a frequent invited speaker at international software conferences and user groups. He’s author of .NET Gotchas (O’Reilly), coauthor of the 2007 Jolt Productivity award-winning book Practices of an Agile Developer (Pragmatic Bookshelf),
OO and functional style can complement each other.
Object-oriented (OO) programming has become the de facto standard, but
with lambda expressions in Java, we can pull a few more techniques out of
our bag of design tricks. In Java, OO and functional style can now complement
each other and can nicely interplay. We can use these to create lightweight
designs that are flexible to change and easier to extend.
using lambda expressions to replace class hierarchies antonymous inner classes and interfaces.
We can replace interfaces, class hierarchies, and anonymous inner classes
with concise code. We need fewer lines of code to get the same job done, and
we can quickly try out new ideas.
Use lightweight functions to replace objects.
Separating Concerns Using Lambda ExpressionsIn this chapter lambda expressions bring to life some neat design ideas; where
we often use objects, we’ll instead use lightweight functions. We’ll use lambda
expressions to easily separate logic from functions, making them more
extensible. Then we’ll apply them to delegate responsibilities and implement
the decorator pattern in just a couple of lines of code. Finally we’ll use them
to turn mundane interfaces into fluent, intuitive interfaces.
Using higher-order functions can let us reuse code, replacing classes.
Exploring Design ConcernsWe often create classes to reuse code; we have good intentions, but it’s not
always the right choice. By using higher-order functions, we can accomplish
the same goals without needing a hierarchy of classes.
Example: sum asset values.
Design idea: separation of concerns.
Old version: mix several concerns in one method.
Let’s start with an example to sum asset values as a way to illustrate the
design idea of separation of concerns. We’ll build it in iterations. The design
we first create will mix multiple concerns in one method, but we’ll quickly
refactor to make the method more cohesive. Let’s start with an Asset class.
package fpij;
public class Asset {
public enum AssetType { BOND, STOCK };
private final AssetType type;
private final int value;
public Asset(final AssetType assetType, final int assetValue) {
type = assetType;
value = assetValue;
}
public AssetType getType() { return type; }
public int getValue() { return value; }
}
JavaBean code.
Asset is a simple JavaBean with two properties: type and value. Suppose we’re
asked to total the values of all the assets given—let’s write a method for that
in a AssetUtil class.
In AssetUtil class we have a method called totalAssetValues.
public static int totalAssetValues(final Listassets) { return assets.stream() .mapToInt(Asset::getValue) .sum(); }
Use lambda expressions to transform the List of Assets into a Stream, then use a mapToInt method to map that into a Stream of values. Finally, reducing the values in this value stream gets the total.
We used the convenience of lambda expressions within this function. We
transformed the List of Assets into a Stream, then mapped that into a Stream of
values using the mapToInt() method. Finally we reduced or totaled the values
in this stream to arrive at a single value using the sum() method. Let’s define
some assets to try out the code.
Establish Asset list.
final Listassets = Arrays.asList( new Asset(Asset.AssetType.BOND, 1000), new Asset(Asset.AssetType.BOND, 2000), new Asset(Asset.AssetType.STOCK, 3000), new Asset(Asset.AssetType.STOCK, 4000) );
Here’s a call to the totalAssetValues() method using these assets
System.out.println("Total of all assets: " + totalAssetValues(assets));
Employing lambda expression to solve this problem is good so far.
However, the aforementioned method is tangled with several concerns: how to iterate, what to total, and how to total.
Poor reusing was caused by this entangled logic of how and what.
Getting Entangled with the ConcernsIt’s good we employed lambda expressions to write the totalAssetValues() method—
we used fluent iterators and favored immutability. But let’s shift our attention to
the design of the method itself. It’s tangled with three concerns: how to iterate,what to total, and how to total. This entangled logic will result in poor reuse. Let’s
see how.
想象一下,我们被要求只计算债券资产。 快速浏览一下 totalAssetValues() 方法后,我们意识到它几乎可以满足我们的所有需求。 为什么不复制并粘贴该代码? 毕竟集成开发环境为诸如此类的麻烦提供键盘快捷键是有原因的,对吧?
Imagine we’re asked to total only the bond assets. After a quick glance at the
totalAssetValues() method, we realize it does almost everything we need. Why not
copy and paste that code? After all there’s a reason the integrated development
environments have gone through the trouble to provide keyboard shortcuts
for that, right?
Let’s take a glance at the code
We’ll leave totalAssetValues() intact, but duplicate it and modify the new version,
like so:
public static int totalBondValues(final Listassets) { return assets.stream() .mapToInt(asset -> asset.getType() == AssetType.BOND ? asset.getValue() : 0) .sum(); }
Almost the same code. But let’s use a filter method to extract one bonds, instead of crowding some logic within one lambda expression. Before that, we just run the code to make sure it works.
The only difference, other than their names, between totalBondValues() and totalAssetValues()
is in the lambda expressions we send to the mapToInt() function. In
this newer method we pick the price of the asset if it’s a bond; otherwise we
use a 0 for the price. Instead of crowding the logic within that one lambda
expression we could use a filter() method to extract only bonds, and leave the
lambda expression that was passed to the mapToInt() method untouched from
the version copied from the totalAssetValues() method.
Run the code without filter method.
Let’s call this version of the method and make sure it works.
System.out.println("Total of bonds: " + totalBondValues(assets));
Copy paste the code to total only stocks.
As fate may have it, now we’re asked to total only stocks. We know it’s
morally wrong to copy and paste code, but no one’s looking.
public static int totalStockValues(final Listassets) { return assets.stream() .mapToInt(asset -> asset.getType() == AssetType.STOCK ? asset.getValue() : 0) .sum(); }
Run the code
System.out.println("Total of stocks: " + totalStockValues(assets));
Is it time to celebrate because we use lambda expressions and make it work?
Hey, it works and we even used lambda expressions. Time to call it done and
celebrate?
However, we violated DRY(Don’t Repeat Yourself) principle.
Not quite; if our geeky friends discover the duplicates, they’ll no longer hang
out with us. We need a better design: one that’s DRY, one that’ll make
mothers proud.
So we should refactor.
Refactoring to Separate a Key ConcernSeparate the “what to total” from iteration
Let’s revisit the three methods. They share two out of the three concerns we
mentioned earlier. The iteration and the way to total are the same. The “what
to total” concern is different and is a good candidate to separate out of these
methods.
Design pattern: strategy pattern
What is strategy pattern? There is a family of algorithms or objects to select, instead of implementing a single algorithm directly.
source: https://en.wikipedia.org/wiki/Strategy_pattern
In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.[1]
Now let’s refactor the code: receive a functional interface.
This seems like a good place for the strategy pattern. We often create interfaces
and classes to implement that pattern in Java, but here lambda expressions
will give us a design edge.
Let’s refactor the three methods into one that takes a functional interface as
a parameter.
public static int totalAssetValues(final Listassets, final Predicate assetSelector) { return assets.stream() .filter(assetSelector) .mapToInt(Asset::getValue) .sum(); }
This version receives two parameters: list of assets and a Predicate interface to evaluate whether an asset should be considered.
This refactored version of totalAssetValues() takes two parameters: the list of
assets and a Predicate to evaluate whether an asset should be considered
Reuse the common Predicate interface instead of creating our own interface.
Employ lambda expressions instead of creating anonymous inner classes.
At first this may look like what we would’ve done all along in Java, but it’s
different in a few ways. Rather than creating our own interface, we’ve reused
the java.util.function.Predicate interface from the Java Development Kit (JDK).
Furthermore, instead of creating classes or anonymous inner classes, we can
pass lambda expressions to the refactored version of the totalAssetValue() method.
See the procedure of the method aforementioned.
Pass the Predicate we received on to the filter method and use method reference.
Let’s dig into this refactored version. We filtered the list of assets using the
filter() method, then mapped the assets to their prices using the mapToInt()function, and totaled them. We simply passed the Predicate we received on to
the filter() method and used method reference for the mapToInt()’s argument.
What is under the hood of the filter using Predicate?
The filter method takes care of picking only the assets we’re interested in.
Under the hood, it calls the given Predicate’s test() method to make that decision.
If the selector accepted the asset, we use its value to total further down in
the chain.
Wow, amazing usage of this strategy pattern!
With this refactoring, we turned the three normal methods into one higherorder
function that depends on a lightweight strategy to handle a configurable
concern, as the next figure illustrates
picture
Just run the code.
Let’s use this refactored version of totalAssetValues() to total the values of all the
assets.
System.out.println("Total of all assets: " +
totalAssetValues(assets, asset -> true));
Two parameters here. The second one is a simple lambda expression which returns a boolean true here to total all the assets.
We invoke the totalAssetValues() function, passing it the list of assets as the first
argument and a succinct lambda expression as the second argument. As the
function iterates over the assets, it invokes the lambda expression for each
asset, asking if the asset’s value should be included in the total. Since we
want to total all the assets, we return a boolean true here.
Abide by the OCP principle without duplicating code.
We’ve used the open/closed principle in this refactored design. We can easily
change the selection criteria without changing the method, as we’ll see next.
Use different lambda expression to compute different assets.
Let’s reuse the function to compute the total of only bonds and then the total
of only stocks. We’ll pass different lambda expressions as the second argument
to the totalAssetValues() function.
System.out.println("Total of bonds: " +
totalAssetValues(assets, asset -> asset.getType() == AssetType.BOND));
System.out.println("Total of stocks: " +
totalAssetValues(assets, asset -> asset.getType() == AssetType.STOCK));
Use lambda expressions to keep concerns and method divided. Separate them properly and correctly.
We’ve used lambda expressions to separate the concern from the method.
This is a simple use of the strategy pattern, but without the burden of creating
extra classes. This pattern does require a bit more from the higher-order
function’s users—they have to chose the selection logic. However, they can
save these lambda expressions into variables and reuse them if they desire.
Let’s move to the class level.
Delegating Using Lambda ExpressionsWe focused on concerns at a method level in this section; let’s apply that
technique at the class level next.
Delegation is better than inheritance from a reuse point of view.
Creating a DelegateWe used lambda expressions and the strategy pattern to separate a concern
from a method. We can also use them to separate a concern from a class.
From a reuse point of view, delegation is a better design tool than inheritance.
With delegation it’s easier to vary the implementation we rely on, and we can
plug in a different behavior more dynamically. This can help vary the behavior
of classes independent of the behavior of the parts they depend on, and make
the design more flexible without forcing a deep class hierarchy.
Delegate part of the responsibility to lambda expressions and method references.
Rather than delegating part of the responsibility to another class, we can
delegate it to lambda expressions and method references. This will further
reduce class proliferation. Let’s explore that idea with an example; we’ll startwith a class, CalculateNAV, that performs financial calculations with data from
a web service.
code here
package fpij;
import java.math.BigDecimal;
import java.util.function.Function;
public class CalculateNAV {
public BigDecimal computeStockWorth(
final String ticker, final int shares) {
return priceFinder.apply(ticker).multiply(BigDecimal.valueOf(shares));
}
//... other methods that use the priceFinder ...
private Function priceFinder;
public CalculateNAV(final Function aPriceFinder) {
priceFinder = aPriceFinder;
}
public static void main(String[] args) {
final CalculateNAV calculateNav = new CalculateNAV(YahooFinance::getPrice);
System.out.println(String.format("100 shares of Google worth: $%.2f",
calculateNav.computeStockWorth("GOOG", 100)));
}
}
Task: One class named CalulateNAV performs financial calculations with data from a web service.
In the computeStockWorth() method we request the price of a ticker from a (yet
to be defined) priceFinder and determine the net worth based on the number of
shares. The CalculateNAV may have other methods to perform other calculations,
such as yield, with the price returned by the priceFinder. That’s a reason for the
priceFinder to be a field in the class rather than a parameter to one particular
method of CalculateNAV.
Function interface is a good lightweight fit for us to decide what kind of object we need in priceFinder.
Now we need the priceFinder; we have to decide what kind of object it will be.
We want to send in a ticker symbol and receive a price, hopefully obtained
from a web service. The java.util.function.Functionfunctional interface seems
like a good lightweight fit for our needs. Its abstract method can take in a value
and return another value, of possibly a different type. Let’s use that to define
the field.
private FunctionpriceFinder;
We’ve used apply() method of the Function interface.
Initialize the priceFinder through a constructor injection.
Use the dependancy inversion principle(DIP)
In the computeStockWorth() method we’re already using the Function interface’s
’apply() method. Let’s initialize the field through a constructor injection rather
than coupling to an implementation directly within the class. In effect we’re
using dependency injection and the dependency inversion principle. Instead
of embedding an implementation, we’ll separate the concern and rely on an
abstraction. This will make the code more extensible and help shorten the
coding and testing time. Here’s the constructor for the CalculateNAV class.
public CalculateNAV(final FunctionaPriceFinder) { priceFinder = aPriceFinder; }
We need to implement a call to the web service.
Stubbing the Web ServiceWe’re all set to use CalculateNAV, but we need to implement a call to the web
service. Let’s look into that next.
Stub the web service without depending on external services.
We’re focused on the design of CalculateNAV; we want to quickly run it and get
feedback. When test-driving the design of this class using unit tests, we don’t
want to depend on external services—that would make the tests brittle. We
want to stub the web service.
Lambda expressions help us create a stub fluently and easily.
In general, though, creating a stub (or mock) in Java can be arduous and we
often rely on libraries. Thanks to the lambda expressions and their fluency,
this just got easier. Let’s create a unit test to try out our computeStockWorth()
method, stubbing away the implementation of the apply() method.
Now is the JUnit4 test
@Test
public void computeStockWorth() {
final CalculateNAV calculateNAV =
new CalculateNAV(ticker -> new BigDecimal("6.01"));
BigDecimal expected = new BigDecimal("6010.00");
assertEquals(0,
calculateNAV.computeStockWorth("GOOG", 1000).compareTo(expected),
0.001);
}
Pass a lambda expression to the constructor to create a test.
Creating the test was effortless. We passed a lambda expression to the CalculateNAV
constructor—this is lightweight stubbing of the web service. From
within the lambda expression, we returned a contrived value for the price in
response to the call. Then, in the test, we asserted that the computeStockWorth()
returned the expected result, within a tolerance of 0.001, for a given ticker
and the number of shares.
It’s easy to add other tests without really spending time to create the code to talk to the web service.
We can also assert that the ticker passed to the lambda expression is the right
one. We can take this further quite easily to add other tests—for example, an
exception test to ensure code properly handles web-service failures. We can
do all this without really spending time to create the code to talk to the web
service, but instead merely stubbing away the implementation. Let’s run the
test and ensure JUnit reports it passing.
Code using JUnit4 test
package fpij;
import org.junit.Test;
import java.math.BigDecimal;
import junit.framework.JUnit4TestAdapter;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertEquals;
public class CalculateNAVTest {
@Test
public void computeStockWorth() {
final CalculateNAV calculateNAV =
new CalculateNAV(ticker -> new BigDecimal("6.01"));
BigDecimal expected = new BigDecimal("6010.00");
assertEquals(0,
calculateNAV.computeStockWorth("GOOG", 1000).compareTo(expected),
0.001);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(new JUnit4TestAdapter(CalculateNAVTest.class));
}
//...
}
Stub away the dependency to the web service.
Integrating with the Web ServiceTesting the code was quick; we easily stubbed away the dependency to the
web service, which helped to rapidly develop and test the code. But we can’t
call it done until we run it with a real web service. That’s our next task.
Talking to the real web service is almost as easy—let’s invite Yahoo! to the
party.
public static void main(String[] args) {
final CalculateNAV calculateNav = new CalculateNAV(YahooFinance::getPrice);
System.out.println(String.format("100 shares of Google worth: $%.2f",
calculateNav.computeStockWorth("GOOG", 100)));
}
Using a method reference to YahooFinance class’s getPrice method, We implement it.
Rather than stubbing away the implementation here, we pass a method reference
to YahooFinance’s getPrice() method. We need to implement that method
to complete this task.
package fpij;
import java.math.BigDecimal;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Random;
public class YahooFinance {
public static BigDecimal getPrice(final String ticker) {
try {
final URL url =
new URL("http://ichart.finance.yahoo.com/table.csv?s=" + ticker);
final BufferedReader reader =
new BufferedReader(new InputStreamReader(url.openStream()));
final String data = reader.lines().skip(1).findFirst().get();
final String[] dataItems = data.split(",");
return new BigDecimal(dataItems[dataItems.length - 1]);
} catch(Exception ex) {
throw new RuntimeException(ex);
}
}
}
A request was sent to the Yahoo web service in the getPrice method.
Parse the response to extract the information we need.
In the getPrice() method we send a request to the Yahoo! web service and parse
the response to extract the stock price. The data we’re looking for is in the
second line of the multiline response from Yahoo!. Instead of reading line by
line from the BufferedReader, we use the new lines() method, an internal iterator
that returns a Stream. From this we extract the second line and extract the
data we desire. Let’s now exercise the call to the computeStockWorth() method we
wrote.
We have to figure out a way to handle exceptions.
We need to find a right place to handle them.
We have to figure out a way to deal with exceptions that may arise when
calling the web service. Suppressing exceptions with empty catch blocks or
printing them in arbitrary places is pure evil. Rather than dealing with
exceptions within lambda expressions, we have to find the right place to
handle them. That requires us to rethrow the exceptions so they can be
handled upstream.
Lambda 表达式和方法引用可以抛出检查异常,前提是这些异常是在它们所代表的功能接口的抽象方法中使用 throws 子句声明的.
作为一种解决方法,我们将异常封装到未经检查的 RuntimeException
Lambda expressions and method references can throw checked exceptions
only if those exceptions are declared using the throws clause in the abstract
method of the functional interface they stand in for. Since the Function interface’s
apply() method doesn’t specify any expected exceptions, we can’t directly
throw the checked exception in this example. As a workaround, we wrapped
the exception into the unchecked RuntimeException. The lambda expression now
simply passes the exception through, and upstream in the code we’ll have to
handle it. Any runtime exception that is not handled, of course, will abruptly
terminate the application.
Wow, Learned a lot about delegation of outside dependencies, using lambda expressions and method references.
We delegated part of the responsibility of our class using lambda expressions
and method references in this example, as the next figure demonstrates.
Picture
Benefits of delegation and stub.
Help vary the implementation of the call to other dependencies.
Stub them away to run and test code.
其他The approach we took helped vary the implementation of the call to the web
service and stub it away. Next we’ll use lambda expressions to combine
multiple behaviors.
2022年5月7日晚上吃饭期间,看的是Google的CEO Sundar Pichai在Stanford的访谈。主持人提问质量很高,控场水平不错。Sundar的性格很讨喜,平易近人。
来源:Youtube
总结Stanford Graduate School of Business
“You have to encourage innovation. Companies become more conservative in decision making as you grow…be okay with failure and reward effort, not outcomes.” In this View From The Top interview, CEO of Google and Alphabet, Sundar Pichai, speaks to Archana Sohmshetty, MBA '22, about the impact of access to technology, humanity’s challenge to harness it, and how Google is sustainably defining the future of work. “When you see the appetite and the desire for people to make their lives better by gaining access to technology, that is what compels me to go beyond.” says Pichai.
2022年5月21日下午才得以发布这篇blog,原因是5月比较忙碌,todo list上有很多任务需要处理。
之前关于mock和stub的使用还是在 TDD of JavaScript里面学习的,然后一边google一边学会了使用Java中的Mockito来mock。以此完成项目的需求。
现在回头看,在FP in java中系统学习一遍,角度不同,侧重点不同,体会更深。
果然,项目中实践 + 好书是提升能力的好方法。
希望对读者有启发。
参考Functional Programming in Java: Harnessing the Power Of Java 8 Lambda Expressions 1st Edition:https://www.amazon.com/Functional-Programming-Java-Harnessing-Expressions/dp/1937785467
source code: https://pragprog.com/titles/vsjava8/functional-programming-in-java/



