Contract::Declare
Contract::Declare is a simple and lightweight system for defining typed contracts (interfaces) in Perl.
It provides a small DSL to specify method arguments and return types, with optional runtime validation.
Features
- Define strict typed interfaces (contracts) for your classes
- Optional runtime checking of method arguments and return values
- Minimalistic DSL:
contract,interface,method,returns - Integrates with
Role::Tinyfor easy role-based design - No heavy dependencies, very fast
Installation
Install via CPAN:
cpanm Contract::Declare
Or manually:
perl Makefile.PL
make
make test
make install
Quick Start
package MyInterface;
use Contract::Declare;
use Standard::Types qw(Int Str);
contract 'MyInterface' => interface {
method add_number => (Int), returns(Int);
method get_name => returns(Str);
};
package MyImpl;
sub new { bless {}, shift }
sub add_number { my ($self, $x) = @_; return $x + 1 }
sub get_name { return "example" }
# Using the contract
my $impl = MyImpl->new;
my $obj = MyInterface->new($impl);
say $obj->add_number(41); # prints 42
say $obj->get_name; # prints "example"
Environment Variables
| Variable | Description |
|:---------|:-------------|
| CONTRACT_DECLARE_CHECK_TYPES | Enables runtime validation of method arguments and return values if set to true |
| CONTRACT_DECLARE_KEEP_CONTRACT | Keeps contract definitions in memory after building if set |
Example:
export CONTRACT_DECLARE_CHECK_TYPES=1
Contributing
Bug reports and pull requests are welcome!
Please submit issues and feature requests via GitHub Issues.
License
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See the Artistic License 1.0 for details.
Author
Alexander Ponomarev (shootnix@gmail.com)
Project: GitHub Repository