Best practice for adding a bidirectional relation in OO model

前端 未结 5 1499
無奈伤痛
無奈伤痛 2021-02-04 09:24

I\'m struggling to come up with a good way of adding a bidirectional relation in OO model. Let\'s say there is a Customer who can place many Orders, that is to say there is a on

5条回答
  •  甜味超标
    2021-02-04 09:28

    If you are maintaining the bidirectional relationship in Customer.placeOrder(Order), why don't you do the same thing in Order.setCustomer(Customer)?

    class Order {
        private Customer customer;
        public void setCustomer (Customer c) {
            customer = c;
            c.getOrders().add(this);
            // ... or Customer.placeOrder(this)
        }
    }
    

    It seems like duplicating code but it solves the problem. The simpler thing to do though is to avoid bidirectional relationships where possible.

提交回复
热议问题