Reputation: 515
This feels like such a basic question but this is all new for me:
I have a Person and Room class, both of which have a list of Item objects.
public class Person{
private ArrayList<Item> items;
public Person() {
items = new ArrayList<>();
}
public void addItem(){
...
}
public void removeItem(){
...
}
}
public class Room {
private ArrayList<Item> items;
public Room () {
items = new ArrayList<>();
}
public void addItem(){
...
}
public void removeItem(){
...
}
}
The item methods e.g. addItem() are duplicated in both the Room class and the Person class which wasn't very nice. I thought about making a separate Inventory class which has a list of items and item methods and then every room and person would have an inventory.
But then I wouldn't be able to call the Item methods from a Person or Room if I use a private Inventory field.
What's the best way to stop duplication here? Thanks in advance!
Upvotes: 2
Views: 107
Reputation: 31648
You are right. Making a separate inventory class would be a good OOP design.
I'm glad you didn't say making a parent class to Room
and Person
since while that would save you the duplication, Rooms and Person's aren't related so they shouldn't really be related in an Object Oriented sense either.
You can use delegation to delegate the add/remove items to your Inventory
field.
public class Room {
private Inventory inventory = new Inventory();
public void addItem(Item item) {
inventory.addItem(item);
}
public void removeItem(Item item) {
inventory.removeItem(item);
}
}
EDIT
Some people are proposing exposing the Inventory and then having a public add/remove methods on that person.getInventory().addItem(item)
. I think that would violate the Law of Demeter
Upvotes: 7
Reputation: 2957
Depending what your business domain is, you could have an abstract storage container class too that they both inherit from. The abstract storage container would have the methods on it, so you could still call them directly.
You also could give both classes an empty interface of IStorageContainer and then create a new static class with a static method that took in the first parameter of IStorageContainer.
Then you could call AddItem(thisPerson, item) and RemoveItem(thisPerson, item) but be able to reuse those two methods for both classes, using the same code and implementation.
Upvotes: 0
Reputation: 1429
I think the inventory class is the best way to go here. You would be able to use the item methods by creating a getter for the inventory inside Person
and Room
.
Upvotes: 0