I am trying to design an API which involves book a transaction to the system. The system will then generate a transaction ID that uniquely identifies the transaction.
I would like to define the Transaction class as a immutable one, like this:
public class Transaction {
private final double quantity;
private final BigDecimal price;
public Order(double quantity, BigDecimal price) {
this.quantity = quantity;
this.price = price;
}
public double getQuantity() {
return quantity;
}
public BigDecimal getPrice() {
return price;
}
}
The client call the API to create a new transaction:
public void storeTransaction(Transaction t)
But if I do this, how can I store the generated transaction ID?
1. Option 1
I can add an mutable state to the transaction class:
public class Transaction {
private final double quantity;
private final BigDecimal price;
private String transactionID;
public Order(double quantity, BigDecimal price) {
this.quantity = quantity;
this.price = price;
}
public double getQuantity() {
return quantity;
}
public BigDecimal getPrice() {
return price;
}
public String getTransactionID() {
return transactionID;
}
public void setTransactionID(String id) {
transactionID = id;
}
}
But this will make the Transaction class mutable.
Option 2
I can keep using the immutable Transaction and expose the API like this:
public String storeTransaction(Transaction t)
So instead of save the transaction id in the Transaction class, I could return it to our API user. But this does not look perfect for me as well because the user has to maintain an ID->Transaction relationship.
What is the best practice for designing this type of scenario?
Aucun commentaire:
Enregistrer un commentaire