User Tools

Site Tools


at-m42:casestudies:cs04

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
at-m42:casestudies:cs04 [2009/04/15 09:00] eechrisat-m42:casestudies:cs04 [2011/01/14 12:59] (current) – external edit 127.0.0.1
Line 8: Line 8:
 The adventure game first appeared in [[at-m42:lecture4#case_studyan_adventure_game|Case Study 1]] in [[at-m42:lecture4|Lecture 4]]. There we showed how ''List''s and ''Map''s can be combined to produce data structures to manage the book-keeping required in a game. There, the data maintained in the collections where simple strings. in [[at-m42:casestudies:cs02|Case Study 2]] we enhanced the capabilities of the system by making use of procedural code and closures. A text-based menu was introduced to support user interaction. later in [[at-m42:casestudies:cs03|Case study 3]], we used objects with more interesting state information and behaviours to represent the game, the players and items. We also removed any input/output responsibilities from them and introduces another //action// class for this purpose.  The adventure game first appeared in [[at-m42:lecture4#case_studyan_adventure_game|Case Study 1]] in [[at-m42:lecture4|Lecture 4]]. There we showed how ''List''s and ''Map''s can be combined to produce data structures to manage the book-keeping required in a game. There, the data maintained in the collections where simple strings. in [[at-m42:casestudies:cs02|Case Study 2]] we enhanced the capabilities of the system by making use of procedural code and closures. A text-based menu was introduced to support user interaction. later in [[at-m42:casestudies:cs03|Case study 3]], we used objects with more interesting state information and behaviours to represent the game, the players and items. We also removed any input/output responsibilities from them and introduces another //action// class for this purpose. 
  
-In the first two iterations of this case study, we revisit the same case study and use class inheritance to model not just items with a name, description and values, but items in general. As with the earlier versions, we use containers to help model the relationships established between objects. Similarly we continue to make use of unit tests. In the [[third iteration]], we address the problem of error detection and user feedback as well as enhancing the functionality of the system. Finally, in the [[last iteration]], we demonstrate how easy it is to use Groovy to police constraints placed on the model.+In the first two iterations of this case study, we revisit the same case study and use class inheritance to model not just items with a name, description and values, but items in general. As with the earlier versions, we use containers to help model the relationships established between objects. Similarly we continue to make use of unit tests. In the [[#iteration_iiiprovide_user_feedback|third iteration]], we address the problem of error detection and user feedback as well as enhancing the functionality of the system. Finally, in the [[#iteration_ivenforce_constraints|last iteration]], we demonstrate how easy it is to use Groovy to police constraints placed on the model.
  
 An index to the source code for all the examples in this case study is [[/~eechris/at-m42/Case-Studies/case-study-04|available]]. An index to the source code for all the examples in this case study is [[/~eechris/at-m42/Case-Studies/case-study-04|available]].
Line 774: Line 774:
       game.addItem(item)       game.addItem(item)
       actual = game.pickupItem(item.id, player.id)       actual = game.pickupItem(item.id, player.id)
-      println actual 
       }       }
             
Line 782: Line 781:
       }       }
 </code> </code>
-===== Exercises =====+Since Groovy's testing system is so easy to use, it encourages us to do more testing. For example, we can impose constraints on the relationships that exist among objects rather than on object in isolation. The relational constraints start at some object and then follow architectural links to other objects before applying some test. For example, we can assert that if we navigate from any ''Item'' being carried by a ''Player'', then the ''inventory'' of that ''Player'' must contain a reference to an ''Item'' with which we started. In other words, any ''Item'' being carried by a ''Player'' must be consistent. 
 + 
 +This is an example of a //loop variant//. although it does not concern us here, loop invariants are widely used in formal approaches to software development where proof of correctness is important. For our purposes, we just need to demonstrate that if we start at some object and follow a sequence of object links, then we arrive back at the same object. The object diagram of Figure 4 illustrates this.  
 + 
 +{{:at-m42:casestudies:loop-invariant.png|An Item-Player loop invariant.}} 
 + 
 +**Figure 4**: An Item-Player loop invariant. 
 + 
 +The figure shows that if we start from a given ''Item'' and navigate to its ''Player'', then we should find the ''Item'''s id is a key in the ''Player'''s map of carried items. For the model to be consistent, the associated value for that key should be the ''Item'' with which we started. We code the invariant check in Groovy as: 
 +<code groovy> 
 +// class: Game 
 +    private void checkItemCarrierLoopInvariant(String methodName) { 
 +    def items inventory.values().asList() 
 +     
 +    def carriedItems items.findAll{ item -> item.carrier !null } 
 +     
 +    def allOK carriedItems.every { item -> 
 +    item.carrier.inventory.containsKey(item.id) 
 +    } 
 +     
 +    if (! allOK ) { 
 +    throw new Exception("${methodName}: Invariant failed"
 +    } 
 +    } 
 +</code> 
 + 
 +Since the violation of an invariant indicates that a serious error has occurred, we terminate the system by throwing an ''Exception'' with a suitable error message. Notice that we do not declare that the method throws an ''Exception'' (see [[at-m42:Exceptions]]). 
 + 
 +As before, we only check methods that are likely to cause a violation. In this case it is just the method ''pickupItem''
 + 
 +<code groovy> 
 +// class: Game 
 +    // ... 
 +        if (player.inventory.size() < Player.LIMIT) { 
 +         player.pickUp(item) 
 +         this.checkItemCarrierLoopInvariant('Game.pickupItem'
 +        message 'Item picked up' 
 +        } 
 +        else { 
 +        message 'Cannot pickup: player has reached limit' 
 +        } 
 +    // ... 
 +</code> 
 + 
 +Before we finish, we must create at least one unit test to check that the expected ''Exception'' is thrown. this turns out to be problematic since we have coded the ''pickUp'' method in the ''Player'' class to ensure that the loop invariant is not violated. 
 + 
 +One solution is to create a ''MockPlayer'' subclass whose redefined ''pickUp'' method as the required abnormal behaviour: 
 +<code groovy> 
 +class MockPlayer extends Player { 
 +     
 +    Boolean pickUp(Item item) { 
 +    if (! inventory.containsKey(item.id)) { 
 +        //  
 +        // Normal behviour commented out 
 +         // inventory[item.id] item 
 +        item.pickedUpBy(this) 
 +        return true 
 +    } 
 +    else { 
 +    return false 
 +    } 
 +    } 
 + 
 +
 +</code> 
 + 
 +We create a ''MockPlayer'' object in the unit test where a ''Player'' object would normally be expected. 
 + 
 +<code groovy> 
 +// class: GameTest 
 +    void testCheckItemCarrierLoopInvariant() { 
 +      def mockPlayer new MockPlayer(id : 1234, nickname : 'chris',  
 +                email : 'cpj@swan.ac.uk'
 +      game.registerPlayer(mockPlayer) 
 +      game.addItem(book) 
 +      game.addItem(satchel) 
 +       
 +      try { 
 +      game.pickupItem(book.id, mockPlayer.id) 
 +      fail('Expected: Game.checkItemCarrierLoopInvariant: Invariant failed'
 +      } catch (Exception e) { 
 +      // ignore exception 
 +      } 
 +    } 
 +</code> 
 + 
 +Note that the method ''fail'' reports a failure only if the ''Exception'' has not been thrown. The ''MockPlayer'' class is an example of the //mock object// testing design pattern. It avoids polluting normal code with abnormal behaviours. 
 + 
 +Happily all the tests in the ''runAllTests'' script pass. Therefore, at this point, we conduct functional tests by executing a Groovy script from the previous iteration. As expected, no problems occur and we consider this iteration to be finished. 
 + 
  
  
at-m42/casestudies/cs04.1239786046.txt.gz · Last modified: 2011/01/14 12:47 (external edit)