nus-cs2103-AY2122S1 / forum

18 stars 2 forks source link

Instantiating an object with null counted as optional multiplicity? #440

Closed NicolasCwy closed 3 years ago

NicolasCwy commented 3 years ago

Should the association between box -> item have a multiplicity of 0..1 instead of 1 as we are able to instantiate box using Box box = new Box(null).

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Item item1 = new Item();
        Item item2 = new Item();
        Box box1 = new Box(item1);
        Box box2 = new Box(item2);
        item2.setMainCard(new Card());
        item2.addPreviousBox(box1);
        item2.addPreviousBox(box2);
    }
}

class Box {
    private Item item;
    Box(Item item) {
        this.item = item;
    }
}

class Item {
    private List<Box> previousBoxes = new ArrayList<>();
    private Card mainCard = null;
    private Card subCard = null;

    void setMainCard(Card card) {
        this.mainCard = card;
    }

    void setSubCard(Card card) {
        this.subCard = card;
    }

    void addPreviousBox(Box previousBox) {
        previousBoxes.add(previousBox);
    }
}

class Card {

}

image

yucheng11122017 commented 3 years ago

Yes I think the multiplicity should be 0..1 because there is the option to set to be null. Usually unless something in the questions implies that it is a compulsory association or there is a check for null, it is 0..1.

damithc commented 3 years ago

Yes I think the multiplicity should be 0..1 because there is the option to set to be null. Usually unless something in the questions implies that it is a compulsory association or there is a check for null, it is 0..1.

Correct. In a case like this it is possible that the relationship is intended to be compulsory but the implementation is not very defensive. If this happens in the exam, both answers will be accepted. In a real project, you must find out the intended design and capture that in the diagram.

NicolasCwy commented 3 years ago

@damithc @yucheng11122017 Thank you for the clarification