[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: ASSERTIONS: a newbie wants to know
From:       "Jason Voegele" <jason () jvoegele ! com>
Date:       2002-03-21 18:56:24
[Download RAW message or body]

> What are they good for...does Ruby need em? Java just added them and I
> read it is a big thing about Eiffel.

Assertions are simply true/false statements about the current state of a 
running program.  For example, an assertion in a linked list class might be:

    assert { size >= 0 }

You can put such assert statements anywhere in your code, to verify that 
some required condition is true.  If an assertion is not true, typically 
the program will terminate with a diagnostic message.  This is what Java 
implements.

Eiffel's Design By Contract (DBC) mechanism adds a lot on top of basic 
assertions.  For example you can specify preconditions and postconditions 
for any method, you can specify an invariant for a class, etc.  Perhaps 
most importantly, these assertions are inherited by subclasses in a well-
defined manner (achieving Liskov substitutability).  For example (using 
Ruby instead of Eiffel):

class Stack
    def initialize
        @size = 0
        @stack = Array.new
    end

    def push(element)
        pre { !element.nil? }
        post { size = old size + 1 }
        @stack.push(element)
    end

    def pop
        pre { size > 0 }
        post { size = old size - 1 }
        @stack.pop
    end

    invariant { size >= 0 }
end

Preconditions are checked before the method is invoked, postconditions and 
invariants are checked before the method returns.  It is the callers 
responsibility to ensure preconditions are met before calling a method, and 
the methods responsibility to ensure that postconditions and invariants 
hold by the end of the method.  The nice thing is that if you subclass 
Stack and override any of its methods, you must obey the preconditions and 
postconditions specified in the superclass.

Ruby already has a DBC implementation.  You can get it at:

    http://www.rubycentral.com/downloads/dbc.html

You can read more about Design by Contract at:

    http://www.eiffel.com/doc/manuals/technology/contract/page.html

Jason Voegele


[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic