On 26/02/2016 10:16, stepharo wrote:
Alain

can you give two example how to use the contract: ?

I would understand:

     <precondition: [can we pass a block here] >

Stef



Hi Stef,

Yes this is completely inspired by Bertrand Meyer/Eiffel work.
I did an help page on that in the package info description on smalltalkhub with more info, but here is an abstract:

precondition, postconditions, invariants are smalltalk checking methods that returns true or false and check that the object will perform/has performed (pre/post) as expected and is in a coherent state (invariants) .
This is not about program proof but run time checking.

I first tried with a block expressed as text in pragma as you suggest
(and as done in some frameworks with comments)
but it was difficult to use MetaLink with that, and MetaLink is a powerfull tool I wouldn't (and probably couldn't!) rewrite

Adding smalltalk methods is much more powerfull than simple text since it integrates well with standard tools (debugger, browsers etc). Those checks can be compiled in all the methods with the Icecompiler and removed by recompiling the class with the standard compiler.

examples :

an invariant (a condition that is *allways* true) on a MyCollection class would be expressed as a checkIndex method of class MyCollection

like:

checkIndex
        <contract: invariant>
        ^  firstIndex > 0
meaning : on every method call to  MyCollection, firstIndex *must* be > 0
if firstIndex goes <= 0 then the collection has a broken state
this will be checked before and after *every call* of *every method* of MyCollection (except in the constructor an in other contract methods).


a pre condition to a call to add: method
preAdd: anObject
        <contract: #required appliedTo: #( #add: )>
        ^  anObject ~= self
meaning : you must not add a collection to itself
(note: this is just an example and I am not sure of that,
I think it does not make sense to add a collection to itself but may be this is allowed?)
this will be checked before every call to MyCollection>>add:
(note2: appliedTo: allows to apply this check to several specific methods
- I didn't tested it yet but if it does not work then this is a bug)


a post condition that would be checked after every call:
postAdd: anObject
        <contract: #ensured appliedTo: #( #add: )>
        ^  self includes: anObject .
woudl check that after adding an object to a Mycollection, the collection effectivly includes the object.
If it does not, this is reported as an error.

names (checkIndex, preAdd: , postAdd:) are not important, they are like other methods of MyCollection. The important thing is the 'appliedTo' part of the pragma who indicates to which methods the contract applies.





Reply via email to