0
Class Game
Method: addPlayer(param Player)

I would like to create an invariant for my method addPlayer so it verifies that parameter Player exists.

Example:

context Game::addPlayer(pl:Player)
    inv pl->exists( p : Player | p.playerID = pl.playerID )

Not sure if syntax is valid

gogasca
  • 9,283
  • 6
  • 80
  • 125

1 Answers1

2

I´m not going to get into the discussion if the constraint itself makes sense. Just some comments to help you understand OCL in this case.

  1. Invariants are created on classes. They don´t make sense in an operation context.
  2. Probably what you want is an Operation precondition.
  3. "exists" is an operator (existential quantifier) to work on a collection. The point is that you are implicitly creating a collection with the parameter p1 (by doing pl->exists(...), so your constraint will always be true.
  4. A probably better constraint would be the following

Using the allInstances() operation

context Game::addPlayer(pl:Player)
pre : Player.allInstances()->exists(p : Player | p.playerID = pl.playerID )
Richard Tingle
  • 16,906
  • 5
  • 52
  • 77
ASBH
  • 541
  • 2
  • 6