samedi 4 novembre 2017

Sensible one-to-one class relationship

Let's say I have a class Stock representing some basic stock data, and then the additional class StockDetails providing some additional details of a specific stock.

Stock.java

public class Stock {

    private int stockId;
    private String stockCode;
    private String stockName;
    private StockDetail stockDetail;

    public Stock() {
    }

    public Stock(String stockCode, String stockName) {
        this.stockCode = stockCode;
        this.stockName = stockName;
    }

    // ...
}

StockDetails.java

public class StockDetail {

    private Stock stock; // yes or no?
    private String compName;
    private String compDesc;
    private String remark;
    private Date listedDate;

    public StockDetail() {
    }

    public StockDetail(String compName, String compDesc,
            String remark, Date listedDate) {
        this.compName = compName;
        this.compDesc = compDesc;
        this.remark = remark;
        this.listedDate = listedDate;
    }

    // ...
}

Now I am not sure what would be the best way to design this kind of relationship. My concerns are:

  1. Should the Stock have a reference to it's StockDetails and StockDetails have a reference to it's Stock?
  2. If the StockDetails doesn't have a reference to it's Stock, that quite makes no sense, because the StockDetails object is meaningless without the corresponding Stock. However, if it does have, it's pointless and weird to obtain the Stock from it's own details, ie. stockDetails.getStock().
  3. Should the StockDetails be an inner class of the Stock? This again is not ideal, because I would like to access the StockDetails class outside of the Stock.
  4. It's even pointless to be able to instantiate a StockDetails object, without previously having a Stock object. The two should somehow be instantiated together, as they co-exist.

What would be the most sensible way to achieve that kind of relationship?

Aucun commentaire:

Enregistrer un commentaire