Thursday, June 15, 2017

Generics - T extends Class & Interface

Say you have a Transaction object

public abstract class Transaction {
Long transactionId


And you have various transactions,

MoneyTransaction
RewardPointTransaction
CouponTransaction
etc

There are some of these transactions that are  Transferable and some are not

public interface Transferable {
    Long getDestinationAccount();
}

I need to write a common assertion while writing test case.

public void assertTransferableTransactions

takes in lists

expectedTransactions
actualTransactions

I would need transactionId to group the inputs, which is in type Transaction
And the methods to be in tested that are in Transferable

So I could have my assertion like

public static <T extends Transaction & Transferable> void assertTransferrableTransactions(
            List<T> expectedTransactions, List<T> expectedTransactions)

You can have just this method in a test util and avoid the code duplicate throughout all the Transaction tests that are transferable

Note that in
T extends A & B
class name should come first and interfaces follow.
i.e.
<T extends Transferable & Transaction> will give compilation error

No comments:

Post a Comment