Custom constructors

10 views
Skip to first unread message

Thomas Kuehne

unread,
Jul 17, 2018, 9:10:37 AM7/17/18
to Umple-Help
Hi,

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

Please 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 (a cup for shuffling and throwing dice for a dice game) to contain five die objects, hence the 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 are added.
I cannot use "before" either, because then the "dice" array 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.

What am I missing?

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

Any help would be much appreciated and I apologise in advance if the answer could have been found in one of the many examples. I consulted the help pages quite a bit but am unfortunately too pressured for time right now to exhaust all possible places.  

Kind regards,

  Thomas



 





Timothy Lethbridge

unread,
Jul 17, 2018, 11:18:57 AM7/17/18
to Umple-Help
 Hi Thomas,

In addition to the work-around you suggested of passing in the dice, another
possibility would be to simply make the association

 * -> 0..5

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.

By the way, we are transitioning to having questions answered on Stack
Overflow with the 'umple' tag. Just to help get this ball rolling, would you
mind re-posing the question there:
Reply all
Reply to author
Forward
0 new messages