1

I've just started using Umple and have come across a case where neither the "before" nor "after" directives seem to work for injecting code into a constructor.

Consider the following Umple code:

class Cup
{
    * -> 5 Die dice;

    after constructor {
        for (int i=0; i<5; i++)
            dice.add(new Die());
    }

    public void throwDice() {
        for (Die d : dice)
            d.throwDie();
    }
}

I'd like a new cup object (representing a cup for shuffling and throwing dice for a dice game) to contain five die objects, hence the above attempt to inject the respective code using the "after" director with "constructor".

However, this generates the following code for the constructor:

public Cup(Die... allDice)  {
    dice = new ArrayList<Die>();
    boolean didAddDice = setDice(allDice);

    if (!didAddDice) {
        throw new RuntimeException("Unable to create Cup, must have 5 dice");
    }

    // line 36 "model.ump"
    for (int i=0; i<5; i++)
        dice.add(new Die());
    // END OF UMPLE AFTER INJECTION
}

This means, a runtime exception will be thrown before the die objects can be added by my custom code.

I cannot use "before" either, because then the "dice" list will not have been initialised yet.

I realise I could circumvent the problem by passing in five die objects to the constructor, but I'd rather have a parameterless constructor and have everything set up properly within the constructor.

Am I missing something?

I feel a minimum multiplicity should still allow for the minimum number of objects to be created within a parameterless constructor.

I noticed that I can use "lazy" to stop the Umple code generator from adding parameters to constructors when dealing with regular attributes, but this unfortunately does not work for the association " * -> 5 Die dice ".

Any hints would be much appreciated.

1 Answer 1

1

I suggest that you change the association so that it is as follows:

* -> 0..5 Die dice;

In other words, specify the lower bound of the multiplicity on the right hand side to be zero.

Then the constructor wouldn't have that dice argument. Essentially this is the equivalent of 'lazy' for associations. You can then have the constructor populate it in the manner you have suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.