Reputation: 467
I am searching for a design solution to the problem where I have 2 classes which depend on each other such that I have class Customer
and class Order
where:
Customer
can have a list of orders (1-to-N) and an Order
has a designated customer (1-to-1).
What is the best practice to break these kind of dependencies?
Upvotes: 1
Views: 507
Reputation: 857
As a software engineer for approx 2 years, the best I’ve seen for a case like that is to put a shadow definition of one class, without initializing it to anything, simply telling the compiler “hey orders exist”, then defining the other class explicitly, followed by your orders class explicitly. Does that get you in the right direction? Nodes and trees sometimes are modeled this way, and data structure and analysis of algorithms books tend to have decent design solutions to this too.
Upvotes: -1
Reputation: 5829
Assuming you have a dependency as follows:
public class Customer {
private long customerId;
private String name;
private String address1;
// ....
private List<Order> orders;
}
public class Order {
private long orderNumber;
private Date orderDate;
// ... others
private Customer customer;
}
You could create a third class to break the dependency:
public class CustomerOrder {
private final Customer customer;
private final List<Order> orders;
public CustomerOrder(Customer customer) {
super();
this.customer = customer;
this.orders = new ArrayList<Order>();
}
public void addOrder(Order order) {
orders.add(order);
}
public Customer getCustomer() {
return customer;
}
public List<Order> getOrders() {
return orders;
}
}
Now you can drop orders from the Customer class, and customer from the Order class. Or am I misunderstanding your issue?
Upvotes: 3