Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify decision whether to use one object or another in Java

Tags:

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?

like image 701
Robert Strauch Avatar asked Jun 10 '26 21:06

Robert Strauch


2 Answers

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.

like image 127
GhostCat Avatar answered Jun 12 '26 11:06

GhostCat


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...
    }
like image 23
indybee Avatar answered Jun 12 '26 11:06

indybee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!