programming

Entities With Attributes That Are Data Values

Can entities have only attributes that are data values and aren’t collections? What is alternative?

Example 1: collections

Let’s say, that we have entities orders and items. One order have zero or more items. Let’s look implementation, where the item has collection of items for the attribute.

public class Order {
    Long id;
    List<Item> item;
}

public Long getId() {
    return id;
}

public List<Item> getItem() {
    return item;
}
public class Item {
    Long id;
}

public Long getId() {
    return id;
}

Example 2: map alternative

How can we create entities that don’t have collections for attributes? One possibility is that we move the relation between the order and items to a new class. We create a new class OrderMapItem which contains relations between orders and items.

public class OrderMapItem {
    Map<Long,List<Item>> map = new HashMap<>();

    public List<Item> get(Long key) {
        return map.get(key);
    }

    public List<Item> put(Long key, List<Item> value) {
        return map.put(key, value);
    }
}

New order class is without item collection.

public class Order {
    Long id;
}

public Long getId() {
    return id;
}

Difference

Collections Map alternative
get items by calling order.getItem() orderMapItem.get(order.getId())
performance difference test 2 – 3 X faster 2 – 3 X slower
when order is deleted items are automatically removed you have to create additional logic
structure tree flat

Leave a Reply