Class:...duction(3pm)

๐Ÿ“ฆ
version 1.14 ยท 2 versions
  • 1.14 ยท debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking (latest)
  • 1.14 ยท ubuntu jammy
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

โœจ NAME โœจ

okay bestie, welcome to the Class::Contract(3pm) page from the User Contributed Perl Documentation โ€” it's literally Class::Contract - Design-by-Contract OO in Perl. ๐Ÿ’…


๐ŸŽ€ VERSION ๐ŸŽ€

This doc describes version 1.10 of Class::Contract, released February 9, 2001. โญ


๐ŸŒˆ SYNOPSIS ๐ŸŒˆ

Here's the whole vibe in code, bestie:

package ClassName
use Class::Contract;

contract {
  inherits 'BaseClass';

  invar { ... };

  attr 'data1';
  attr 'data2' => HASH;

  class attr 'shared' => SCALAR;

  ctor 'new';

  method 'methodname';
    pre  { ... };
      failmsg 'Error message';

    post  { ... };
      failmsg 'Error message';

    impl { ... };

  method 'nextmethod';
    impl { ... };

  class method 'sharedmeth';
    impl { ... };

  # etc.
};

๐Ÿ’– DESCRIPTION ๐Ÿ’–

๐Ÿฆ‹ Background ๐Ÿฆ‹

Design-by-contract is a software engineering technique where every module in a software system says explicitly what input (or data or arguments) it requires, and what output (or information or results) it guarantees to produce in response. ๐Ÿซถ

These specifications are the "clauses" of a contract between a module and the client software that uses it. If the client software abides by the input requirements, the module guarantees to produce the correct output. So by verifying these clauses at each interaction with a module, the overall behaviour of the system can be confidently predicted. โœจ

Design-by-contract reinforces the benefits of modular design techniques by inserting explicit compile-time or run-time checks on a contract. These checks are most often found in object-oriented languages and are typically implemented as pre-conditions and post-conditions on methods, and invariants on classes.

Note that these features differ from simple verification statements such as the C assert statement. Conditions and invariants are properties of a class, and are inherited by derived classes. ๐Ÿ‘‘

An additional capacity that is often provided in design-by-contract systems is the ability to selectively disable checking in production code. This allows the contractual testing to be carried out during implementation, without impinging on the performance of the final system. ๐Ÿ’…

๐ŸŒธ Adding design-by-contract to Perl ๐ŸŒธ

The Class::Contract module provides a framework for specifying methods and attributes for a class (much like the existing class definition modules Class::Struct, Class::MethodMaker, and Class::Generate). Class::Contract allows both per-object and per-class methods and attributes to be defined. Attributes may be scalar-, array-, hash-, or object-based. ๐ŸŽ€

Class::Contract differs from other class-specification modules (except Class::Generate) in that it also provides the ability to specify invariant conditions on classes, and pre- and post-conditions on methods and attributes. All of these clauses are fully inheritable, and may be selectively disabled. It differs from all other modules in that it has a cleaner, simpler specification syntax, and -- more importantly -- it enforces encapsulation of object attributes, thereby ensuring that the class contract cannot be subverted. ๐Ÿ”ฅ

โœจ Defining classes โœจ

Class::Contract provides an explicit syntax for defining the attributes, methods, and constructors of a class. The class itself is defined using the contract subroutine. contract takes a single argument -- a subroutine reference or a block. That block is executed once and the results used to construct and install the various components of the class in the current package: ๐Ÿฆ‹

package Queue;
contract {
  # specification of class Queue attributes and methods here
};

๐Ÿ“ Defining attributes ๐Ÿ“

Attributes are defined within the contract block via the attr subroutine. Attributes must be given a name, and may also be given a type: SCALAR, ARRAY, HASH, or a class name:

contract {
        attr 'last';                   # Scalar attribute (by default)
        attr 'lest' => SCALAR;         # Scalar attribute
        attr 'list' => ARRAY;          # Array attribute
        attr 'lost' => HASH;           # Hash attribute
        attr 'lust' => MyClass;        # Object attribute
};

For each attribute so declared, Class::Contract creates an accessor -- a method that returns a reference to the attribute in question. Code using these accessors might look like this:

${$obj->last}++;
push @{$obj->list}, $newitem;
print $obj->lost->{'marbles'};
$obj->lust->after('technology stocks');

Attributes are normally object-specific, but it is also possible to define attributes that are shared by all objects of a class. Class objects are specified by prefixing the call to attr with a call to the class subroutine:

class Queue;
contract {
        class attr 'obj_count';
};

The accessor for this shared attribute can now be called either as an object method:

print ${$obj->obj_count};

or as a class method:

print ${Queue->obj_count};

In order to ensure that the clauses of a class' contract (see below) are honoured, both class and object attributes are only accessible via their accessors, and those accessors may only be called within methods belonging to the same class hierarchy. Objects are implemented as flyweight scalars in order to ensure this strict encapsulation is preserved. ๐Ÿ”’

๐Ÿ’œ Defining methods ๐Ÿ’œ

Methods are defined in much the same way as attributes. The method subroutine is used to specify the name of a method, then the impl subroutine is used to provide an implementation for it:

contract {
        attr list => ARRAY;

        method 'next';
            impl { shift @{self->list} };

        method 'enqueue';
            impl { push @{self->list}, $_[1] };
};

impl takes a block (or a reference to a subroutine), which is used as the implementation of the method named by the preceding method call. Within that block, the subroutine self may be used to return a reference to the object on which the method was called. Unlike, regular OO Perl, the object reference is not passed as the method's first argument. (Note: this change occurred in version 1.10) ๐Ÿ˜ญ

Like attributes, methods normally belong to -- and are accessed via -- a specific object. To define methods that belong to the entire class, the class qualifier is once again used:

contract {
        class attr 'obj_count';

        class method 'inc_count';
                impl { ${self->obj_count}++ };
};

Note that the self subroutine can still be used -- within a class method it returns the appropriate class name, rather than an object reference. ๐ŸŒŸ

๐ŸŽ€ Defining constructors ๐ŸŽ€

Class::Contract requires constructors to be explicitly defined using the ctor subroutine:

contract {
        ctor 'new';
            impl { @{self->list} = ( $_[0] ) }
};

Note that the implementation section of a constructor doesn't specify code to build or bless the new object. That is taken care of automatically (in order to ensure the correct flyweight implementation of the object). ๐Ÿงš

Instead, the constructor implementation is invoked after the object has been created and blessed into the class. Hence the implementation only needs to initialize the various attributes of the self object. In addition, the return value of the implementation is ignored: constructor calls always return a reference to the newly created object. ๐Ÿ’–

Any attribute that is not initialized by a constructor is automatically default initialized. By default, scalar attributes remain undef, array and hash attributes are initialized to an empty array or hash, and object attributes are initialized by having their new constructor called (with no arguments). This is the only reasonable default for object attributes, but it is usually advisable to initialize them explicitly in the constructor. โœจ

It is also possible to define a class constructor, which may be used to initialize class attributes:

contract {
        class attr 'obj_count';

        class ctor;
                impl { ${self->obj_count} = 0 };
};

The class constructor is invoked at the very end of the call to contract in which the class is defined. โฐ

Note too that the class constructor does not require a name. It may, however, be given one, so that it can be explicitly called again (as a class method) later in the program:

class MyClass;
contract {
        class attr 'obj_count';

        class ctor 'reset';
                impl { ${self->obj_count} = 0 };
};

# and later...

MyClass->reset;

๐Ÿฆ‹ Defining destructors ๐Ÿฆ‹

Destructors are also explicitly defined under Class::Contract, using the dtor subroutine:

contract {
        dtor;
            impl { print STDLOG "Another object died\n" }
};

As with the constructor, the implementation section of a destructor doesn't specify code to clean up the flyweight implementation of the object. Class::Contract takes care of that automatically. ๐Ÿซถ

Instead, the implementation is invoked before the object is deallocated, and may be used to clean up any of the internal structure of the object (for example to break reference cycles). ๐Ÿ’€

It is also possible to define a class destructor, which may be used to clean up class attributes:

contract {
        class attr 'obj_count';

        class dtor;
            impl { print STDLOG "Total was ${self->obj_count}\n" };
};

The class destructor is invoked from an END block within Class::Contract (although the implementation itself is a closure, so it executes in the namespace of the original class). ๐ŸŒˆ

๐ŸŒˆ Constraining class elements ๐ŸŒˆ

As described so far, Class::Contract doesn't provide any features that differ greatly from those of any other class definition module. But Class::Contract does have one significant difference: it allows the class designer to specify clauses that implement and enforce a contract on the class's interface. ๐Ÿ‘‘

Contract clauses are specified as labelled blocks of code, associated with a particular class, method, or attribute definition. ๐Ÿ’…

โœจ Class invariants โœจ

So your class can have invariants, bestie. And what's an invariant? It's a clause that has to be true at the end of any method call that gets invoked from outside the class itself. Like a vibe check the class has to pass every single time someone pokes it from the outside. ๐Ÿ’…

Say you want to promise that a class's obj_count attribute never dips below zero. Iconic, simple, do it like this:

contract {
        invar { ${self->obj_count} >= 0 };
};

The block that follows invar gets treated exactly as if it were a class method that's automatically invoked after every other method invocation. And if that method returns false? croak gets called with the error message: 'Class invariant at %s failed' โ€” where that %s gets swapped out for the file and line number where the invariant was defined. ๐Ÿ”ฅ

You can customize that error message too, using the failmsg subroutine:

contract {
        invar { ${self->obj_count} >= 0 };
            failmsg 'Anti-objects detected by invariant at %s';
};

Again, that %s becomes the appropriate file name and line number. And heads up โ€” a failmsg can be specified after other types of clause too (see below, we get there, patience babes ๐Ÿซถ).

A class can have as many invariants as it requires, and honestly they can live anywhere throughout the body of the contract. Scatter them like glitter. โœจ


๐ŸŒธ Attribute and method pre- and post-conditions ๐ŸŒธ

Pre- and post-conditions on methods and attributes are specified with the pre and post subroutines respectively. Two little gatekeepers, one at the door and one on the way out.

For attributes: pre-conditions get called before the attribute's accessor is invoked, and post-conditions get called after the reference returned by the accessor is no longer accessible. How does it pull that off, you ask? The accessor returns a tied scalar whose DESTROY method invokes the post-condition. Sneaky. Genius. Obsessed. ๐Ÿ’…

For methods: pre-conditions are tested before the method's implementation is invoked, and post-conditions are tested after the implementation finishes โ€” but before the method's result is returned. And constructors? They're (by definition) class methods, so yeah, they can have pre- and post-conditions just like any other method. No exceptions, no favoritism. ๐Ÿ‘‘

Both types of condition clause receive the same argument list as the accessor or method implementation that they constrain. And both are expected to return a false value if they fail:

contract {
        class attr 'obj_count';
            post { ${&value} > 0 };
              failmsg 'Anti-objects detected by %s';

        method 'inc_count';
            post { ${self->obj_count} < 1000000 };
              failmsg 'Too many objects!';
            impl { ${self->obj_count}++ };
};

Now, key detail, don't skip this one: within the pre- and post-conditions of an attribute, the special value subroutine returns a reference to the attribute itself, so your conditions can check properties of the very attribute they're guarding. It's giving self-aware. ๐Ÿชž

And methods and attributes can have as many distinct pre- and post-conditions as they require, specified in any convenient order. Your house, your rules. ๐ŸŽ€


๐Ÿ”ฎ Checking state changes. ๐Ÿ”ฎ

Post-conditions and invariants can peek at the previous state of an object or the class, via the old subroutine. Inside any post-condition or invariant, old hands you back a reference to a copy of the object or class state, exactly as it was just before the current method or accessor was called. Time travel but make it legal. โณ

So like, an append method could use old to verify that the size of an object changed the way it was supposed to:

contract {
    method 'append';
        post { @{self->queue} == @{old->queue} + @_ }
        impl { push @{self->queue}, @_ };
};

Oh and also โ€” the implementation's return value is also available inside the method's post-condition(s) and the class's invariants, through the subroutine value. In that example up there, the implementation of append returns the new size of the queue (i.e. literally what push returns), so the post-condition could just as well be written:

contract {
    method 'append';
        post { ${&value} == @{old->queue} + @_ }
        impl { push @{self->queue}, @_ };
};

Careful though, bestie: value will return a reference to a scalar or a reference to an array, depending on the context in which the method was originally called. Context matters, always. ๐Ÿฆ‹


๐Ÿ’… Clause control ๐Ÿ’…

Any type of clause can be declared optional:

contract {
        optional invar { @{self->list} > 0 };
        failmsg 'Empty queue detected at %s after call';
};

By default, optional clauses are still checked every time a method or accessor is invoked. But you can also switch them off (and back on) at run-time, using the check method:

local $_ = 'Queue';         # Specify in $_ which class to disable
check my %contract => 0;    # Disable optional checks for class Queue

This (de)activation is restricted to the scope of the hash that gets passed as the first argument to check. And on top of that, the change only affects the class whose name is held in the variable $_ at the time check is called. Which makes it super easy to (de)activate checks for a whole series of classes:

check %contract => 0 for qw(Queue PriorityQueue DEQueue);  # Turn off
check %contract => 1 for qw(Stack PriorityStack Heap);     # Turn on

There's also a special value, __ALL__, that you can use as a (pseudo-)class name:

check %contract => 0 for __ALL__;

That enables or disables checking on every class defined using Class::Contract. But bestie, read this part twice: only clauses that were originally declared optional are affected by calls to check. Non-optional clauses are always checked. No takebacks, no loopholes. ๐Ÿšซ

Optional clauses are typically universally disabled in production code, so Class::Contract hands you a short-cut for that. If the module is imported with the single argument 'production', optional clauses are universally and irrevocably deactivated. In fact, the optional subroutine gets replaced by:

sub Class::Contract::optional {}

so optional clauses impose no run-time overhead at all. Poof, gone, optimized. ๐Ÿงš

In production code, contract checking ought to be disabled completely, and the requisite code optimized away. To do that, simply change:

use Class::Contract;

to

use Class::Contract::Production;

Slay. ๐Ÿซถ


๐Ÿ‘‘ Inheritance ๐Ÿ‘‘

The semantics of class inheritance for Class::Contract classes differ in several respects from those of normal object-oriented Perl. Buckle up, this one's a whole lecture and I'm making it cute. ๐Ÿ’œ

To begin with: classes defined using Class::Contract have a static inheritance hierarchy. The inheritance relationships of contracted classes are defined using the inherits subroutine, inside the class's contract block:

package PriorityQueue;
contract {
        inherits qw( Queue OrderedContainer );
};

Which means ancestor classes are fixed at compile-time โ€” rather than being determined at run-time by the @ISA array. And yes, multiple inheritance is supported. Go off. ๐Ÿ”ฅ

Method implementations are only inherited if they are not explicitly provided. As with normal OO Perl, a method's implementation is inherited from the left-most ancestral class that provides a method of the same name โ€” though with Class::Contract, this is determined at compile-time.

Constructors are a special case, though. Their "constructive" behaviour is always specific to the current class, and hence involves no inheritance under any circumstances. However, the "initialising" behaviour specified by a constructor's impl block is inherited. In fact, the implementations of all base class constructors are called automatically by the derived class constructor โ€” in left-most, depth-first order โ€” and are passed the same argument list as the invoked constructor. This behaviour is much more like that of other OO programming languages (for example, Eiffel or C++). Fancy. ๐ŸŽฉ

Methods in a base class can also be declared as being abstract:

contract {
    abstract method 'remove';
        post { ${self->count} == ${old->count}-1 };
};

Abstract methods act like placeholders in an inheritance hierarchy. Specifically: they have no implementation, existing only to reserve the name of a method and to associate pre- and post-conditions with it. A nameplate. A promise. โœจ

An abstract method cannot be directly called (although its associated conditions may be). If such a method is ever invoked, it immediately calls croak. Therefore, the presence of an abstract method in a base class requires the derived class to redefine that method, if the derived class is to be usable. And to make sure of that, any constructor built by Class::Contract will refuse to create objects belonging to classes with abstract methods. It said no. Periodt. ๐Ÿ’€

Methods in a base class can also be declared as being private:

contract {
    private method 'remove';
        impl { pop @{self->queue} };
};

Private methods may only be invoked by the class or one of its descendants. Inner circle only, iykyk. ๐ŸŽ€


๐ŸŒˆ Inheritance and condition checking ๐ŸŒˆ

Attribute accessors and object methods inherit all post-conditions of every ancestral accessor or method of the same name. Objects and classes also inherit all invariants from any ancestor classes. Meaning: methods accumulate all the post- and invariant checks that their ancestors performed, plus any new ones they define for themselves, and they must satisfy all of them in order to execute successfully. That's a lot of standards to live up to, but honestly? Deserved. ๐Ÿ’…

Pre-conditions are handled slightly differently. The principles of design-by-contract programming state that pre-conditions in derived classes can be no stronger than those in base classes (and may well be weaker). In other words: a derived class must handle every case that its base class handled, but it may choose to handle other cases as well, by being less demanding regarding its pre-conditions. Chill out a little, babe, you're allowed. ๐Ÿฆ‹

Meyers suggests an efficient way to achieve this relaxation of constraints without needing detailed logical analysis of pre-conditions. His solution is to allow a derived class method or accessor to run if either the pre-conditions it inherits are satisfied or its own pre-conditions are satisfied. And that is precisely the semantics that Class::Contract uses when checking pre-conditions in derived classes. No cap. ๐Ÿ”ฅ


๐Ÿ“ A complete example ๐Ÿ“

The following code implements a PriorityStack class, in which elements pushed onto the stack "sink" until they encounter an element with lower priority. Note the use of old to check that object state has changed correctly, and the use of explicit dispatch (e.g. self->Stack::pop) to invoke inherited methods from the derived-class methods that redefine them. Okay it's giving main character energy, let's look:

package PriorityStack;
use Class::Contract;

contract {
    # Reuse existing implementation...
    inherits 'Stack';

    # Name the constructor (nothing special to do, so no implementation)
    ctor 'new';
                   method 'push';
                       # Check that data to be added is okay...
                       pre  { defined $_[0] };
                           failmsg 'Cannot push an undefined value';
                       pre  { $_[1] > 0 };
                           failmsg 'Priority must be greater than zero';

                       # Check that push increases stack depth appropriately...
                       post { self->count == old->count+1 };

                       # Check that the right thing was left on top...
                       post { old->top->{'priority'} <= self->top->{'priority'} };

                       # Implementation reuses inherited methods: pop any higher
                       # priority entries, push the new entry, then re-bury it...
                       impl {
                           my ($newval, $priority) = @_[0,1];
                           my @betters;
                           unshift @betters, self->Stack::pop
                               while self->count
                                  && self->Stack::top->{'priority'} > $priority;
                           self->Stack::push( {'val'=>$newval, priority=>$priority} );
                           self->Stack::push( $_ )  foreach @betters;
                       };

                   method 'pop';
                       # Check that pop decreases stack depth appropriately...
                       post { self->count == old->count-1 };

                       # Reuse inherited method...
                       impl {
                           return  unless self->count;
                           return self->Stack::pop->{'val'};
                       };

                   method 'top';
                       post { old->count == self->count }
                       impl {
                           return  unless self->count;
                           return self->Stack::top->{'val'};
                       };
               };

โœจ FUTURE WORK โœจ

Okay so future work on Class::Contract is gonna concentrate on three areas, bestie:

  1. Improving the attribute accessor mechanism

Lvalue subroutines will be introduced in perl version 5.6. They will allow a return value to be treated as an alias for the (scalar) argument of a return statement. This will make it possible to write subroutines whose return value may be assigned to (like the built-in pos and substr functions). Iconic.

In the absence of this feature, Class::Contract accessors of all types return a reference to their attribute, which then requires an explicit dereference:

        ${self->value} = $newval;
        ${self->access_count}++;

When this feature is available, accessors for scalar attributes will be able to return the actual attribute itself as an lvalue. The above code would then become cleaner:

        self->value = $newval;
        self->access_count++;
  1. Providing better software engineering tools.

Contracts make the consequences of inheritance harder to predict, since they significantly increase the amount of ancestral behaviour (i.e. contract clauses) that a class inherits.

Languages such as Eiffel provide useful tools to help the software engineer make sense of this extra information. In particular, Eiffel provides two alternate ways of inspecting a particular class -- flat form and short form.

"Flattening" a class produces an equivalent class definition without any inheritance. That is, the class is modified by making explicit all the attributes, methods, conditions, and invariants it inherits from other classes. This allows the designer to see every feature a class possesses in one location.

"Shortening" a class, takes the existing class definition and removes all implementation aspects of it -- that is, those that have no bearing on its public interface. A shortened representation of a class therefore has all attribute specifications and method implementations removed. Note that the two processes can be concatenated: shortening a flattened class produces an explicit listing of its complete public interface. Such a representation can be profitably used as a basis for documenting the class.

It is envisaged that Class::Contract will eventually provide a mechanism to produce equivalent class representations in Perl.

  1. Offering better facilities for retrofitting contracts.

At present, adding contractual clauses to an existing class requires a major restructuring of the original code. Clearly, if design-by-contract is to gain popularity with Perl programmers, this transition cost must be minimized.

It is as yet unclear how this might be accomplished, but one possibility would be to allow the implementation of certain parts of a Class::Contract class (perhaps even the underlying object implementation itself) to be user-defined.

๐Ÿ‘‘ AUTHOR ๐Ÿ‘‘

Damian Conway (damian@conway.org)

๐Ÿ› ๏ธ MAINTAINER ๐Ÿ› ๏ธ

C. Garrett Goebel (ggoebel@cpan.org)

๐Ÿ› BUGS ๐Ÿ›

There are undoubtedly serious bugs lurking somewhere in code this funky :-) Bug reports and other feedback are most welcome.

Copyright (c) 1997-2000, Damian Conway. All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the terms of the Perl Artistic License (see http://www.perl.com/perl/misc/Artistic.html)

Copyright (c) 2000-2001, C. Garrett Goebel. All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the terms of the Perl Artistic License (see http://www.perl.com/perl/misc/Artistic.html)


๐Ÿ’– And that's the whole vibe, bestie! This page came from perl v5.36.0, dated 2023-01-22, and it's the Class:...duction(3pm) manpage. Periodt. ๐Ÿ’–