Java Reference
In-Depth Information
The advantage of choosing this approach over the inheritance-based pattern is that instead of
tying the implementation of this algorithm into the
LoanApplication
hierarchy, we can be
much more flexible about where to delegate the functionality to. For example, we may de-
cide that our
Company
class should be responsible for all criteria checking. The
Company
class would then have a series of signatures like
Example 8-25
.
Example 8-25. The criteria methods on a Company
public
public
void
void
checkIdentity
()
throws
throws
ApplicationDenied
;
public
public
void
void
checkProfitAndLoss
()
throws
throws
ApplicationDenied
;
public
public
void
void
checkHistoricalDebt
()
throws
throws
ApplicationDenied
;
Now all our
CompanyLoanApplication
class needs to do is pass in method references to
those existing methods, as shown in
Example 8-26
.
Example 8-26. Our CompanyLoanApplication specifies which methods provide each cri-
terion
public
public class
class
CompanyLoanApplication
CompanyLoanApplication
extends
extends
LoanApplication
{
public
public
CompanyLoanApplication
(
Company company
) {
super
super
(
company:
:
checkIdentity
,
company:
:
checkHistoricalDebt
,
company:
:
checkProfitAndLoss
);
}
}
A motivating reason to delegate the behavior to our
Company
class is that looking up inform-
ation about company identity differs between countries. In the UK, Companies House
provides a canonical location for registering company information, but in the US this differs
from state to state.
Using functional interfaces to implement the criteria doesn't preclude us from placing imple-
mentation within the subclasses, either. We can explicitly use a lambda expression to place
implementation within these classes, or use a method reference to the current class.
We also don't need to enforce inheritance between
EmployeeLoanApplication
and
Person-
alLoanApplication
to be able to reuse the functionality of
EmployeeLoanApplication
in
PersonalLoanApplication
. We can pass in references to the same methods. Whether they
do genuinely subclass each other should really be determined by whether loans to employees