Simplify decision whether to use one object or another in Java
I have a Transaction
class which looks like this:
public class Transaction {
private Transaction parentTransaction;
private long amount;
private String orderNumber;
}
So it has a field which points to another Transaction
.
There is also a method like this:
public void build(Transaction transaction) {
final long amount = transaction.getParentTransaction() == null ? transaction.getAmount() : transaction.getParentTransaction().getAmount();
final String orderNumber = transaction.getParentTransaction() == null ? transaction.getOrderNumber() : transaction.getParentTransaction().getOrderNumber();
// same pattern follows for more fields...
// do other stuff...
}
Depending on whether a parentTransaction
exists, e.g. the amount
field shall be used from the parentTransaction
or the transaction
. What I don't like about this approach is the repetitive usage of the transaction.getParentTransaction() == null ? ...
term.
Is there some pattern or apporach how I could avoid this?
Optional is an option, but I think there is a much simpler solution:
public void build(Transaction transaction) {
Transaction buildFrom = transaction.getParentTransaction() == null ? transaction : transaction.getParentTransaction();
...
String orderNumber = buildFrom.getOrderNumber();
If you don't like that mix of abstractions, you can go one step further and put that ? :
line into a small helper method.
try Optional as suggested by others:
public void build(Transaction transaction) {
Transaction parentTransactionElseTransaction = Optional.of(transaction)
.map(t -> t.getParentTransaction())
.orElse(transaction);
final long amount = parentTransactionElseTransaction.getAmount();
final String orderNumber = parentTransactionElseTransaction.getOrderNumber();
// same pattern follows for more fields...
// do other stuff...
}
public void build(Transaction transaction) {
final long amount = Optional.ofNullable(transaction.getParentTransaction()).orElse(transaction).getAmount();
final String orderNumber = Optional.ofNullable(transaction.getParentTransaction()).orElse(transaction).getOrderNumber();
// same pattern follows for more fields...
// do other stuff...
}
Can use Optional.ofNullable().orElse()
here