1Type::Tiny::Manual::ParUasmesr(3C)ontributed Perl DocumeTnytpaet:i:oTniny::Manual::Params(3)
2
3
4

NAME

6       Type::Tiny::Manual::Params - advanced information on Type::Params
7

MANUAL

9       To get started with Type::Params, please read
10       Type::Tiny::Manual::UsingWithMoo which will cover a lot of the basics,
11       even if you're not using Moo.
12
13   "multiple"
14       The "multiple" option allows you to specify multiple ways of calling a
15       sub.
16
17        sub repeat_string {
18          state $check = signature(
19            multiple => [
20              { positional => [ Str, Int ] },
21              { named => [ string => Str, count => Int ], named_to_list => 1 },
22            ],
23          );
24
25          my ( $string, $count ) = $check->( @_ );
26          return $string x $count;
27        }
28
29        repeat_string(            "Hello",          42  );    # works
30        repeat_string(  string => "Hello", count => 42  );    # works
31        repeat_string({ string => "Hello", count => 42 });    # works
32        repeat_string( qr/hiya/ );                            # dies
33
34       It combines multiple checks and tries each until one works.
35
36   "signature_for"
37       "signature_for" turns "signature" inside out.
38
39       Instead of this:
40
41        sub foobar {
42          state $check = signature( positional => [ Int, Str ] );
43          my ( $foo, $bar ) = $check->( @_ );
44          ...;
45        }
46
47       You do this:
48
49        signature_for foobar => (
50          positional => [ Int, Str ],
51        );
52
53        sub foobar {
54          my ( $foo, $bar ) = @_;
55          ...;
56        }
57
58       Or in Perl 5.20+, you can even do this:
59
60        signature_for foobar => (
61          positional => [ Int, Str ],
62        );
63
64        sub foobar ( $foo, $bar ) {
65          ...;
66        }
67
68   Functions versus Methods
69       For subs which are intended to be called as functions:
70
71        signature( method => 0, ... );
72        signature( ... );                       # this is the default anyway
73
74       For subs which are intended to be called as methods on a blessed
75       object:
76
77        signature( method => Object, ... );
78
79       And for subs which are intended to be called as methods on a class:
80
81        signature( method => ClassName, ... );
82        signature( method => Str, ... );        # less readable, but faster check!
83
84       The following is also allowed, which indicates that the sub is intended
85       to be called as a method, but you don't want to do type checks on the
86       invocant:
87
88        signature( method => 1, ... );
89
90   Mixed Named and Positional Parameters
91       The "head" and "tail" options allow required positional parameters at
92       the start or end of a named parameter list:
93
94        state $check = signature(
95          head  => [ Int ],
96          named => [
97            foo => Int,
98            bar => Optional[Int],
99            baz => Optional[Int],
100          ],
101        );
102
103        $check->( 42, foo => 21 );                 # ok
104        $check->( 42, foo => 21, bar  => 84 );     # ok
105        $check->( 42, foo => 21, bar  => 10.5 );   # not ok
106        $check->( 42, foo => 21, quux => 84 );     # not ok
107
108   Proper Signatures
109       Don't you wish your subs could look like this?
110
111         sub set_name ( Object $self, Str $name ) {
112           $self->{name} = $name;
113         }
114
115       Well; here are a few solutions for sub signatures that work with
116       Type::Tiny...
117
118       Zydeco
119
120       Zydeco is a Perl OO syntax toolkit with Type::Tiny support baked in
121       throughout.
122
123         package MyApp {
124           use Zydeco;
125
126           class Person {
127             has name ( type => Str );
128
129             method rename ( Str $new_name ) {
130               printf( "%s will now be called %s\n", $self->name, $new_name );
131               $self->name( $new_name );
132             }
133
134             coerce from Str via {
135               $class->new( name => $_ )
136             }
137           }
138
139           class Company {
140             has owner ( type => 'Person' );
141           }
142         }
143
144         my $acme = MyApp->new_company( owner => "Robert" );
145         $acme->owner->rename( "Bob" );
146
147       Kavorka
148
149       Kavorka is a sub signatures implementation written to natively use
150       Type::Utils' "dwim_type" for type constraints, and take advantage of
151       Type::Tiny's features such as inlining, and coercions.
152
153         method set_name ( Str $name ) {
154           $self->{name} = $name;
155         }
156
157       Kavorka's signatures provide a lot more flexibility, and slightly more
158       speed than Type::Params. (The speed comes from inlining almost all type
159       checks into the body of the sub being declared.)
160
161       Kavorka also includes support for type checking of the returned value.
162
163       Kavorka can also be used as part of Moops, a larger framework for
164       object oriented programming in Perl.
165
166       Function::Parameters
167
168       Function::Parameters offers support for Type::Tiny and MooseX::Types.
169
170         use Types::Standard qw( Str );
171         use Function::Parameters;
172
173         method set_name ( Str $name ) {
174             $self->{name} = $name;
175         }
176
177       Attribute::Contract
178
179       Both Kavorka and Function::Parameters require a relatively recent
180       version of Perl. Attribute::Contract supports older versions by using a
181       lot less magic.
182
183       You want Attribute::Contract 0.03 or above.
184
185         use Attribute::Contract -types => [qw/Object Str/];
186
187         sub set_name :ContractRequires(Object, Str) {
188             my ($self, $name) = @_;
189             $self->{name} = $name;
190         }
191
192       Attribute::Contract also includes support for type checking of the
193       returned value.
194
195   Type::Params versus X
196       Params::Validate
197
198       Type::Params is not really a drop-in replacement for Params::Validate;
199       the API differs far too much to claim that. Yet it performs a similar
200       task, so it makes sense to compare them.
201
202       •   Type::Params will tend to be faster if you've got a sub which is
203           called repeatedly, but may be a little slower than Params::Validate
204           for subs that are only called a few times. This is because it does
205           a bunch of work the first time your sub is called to make
206           subsequent calls a lot faster.
207
208       •   Params::Validate doesn't appear to have a particularly natural way
209           of validating a mix of positional and named parameters.
210
211       •   Type::Utils allows you to coerce parameters. For example, if you
212           expect a Path::Tiny object, you could coerce it from a string.
213
214       •   If you are primarily writing object-oriented code, using Moose or
215           similar, and you are using Type::Tiny type constraints for your
216           attributes, then using Type::Params allows you to use the same
217           constraints for method calls.
218
219       •   Type::Params comes bundled with Types::Standard, which provides a
220           much richer vocabulary of types than the type validation constants
221           that come with Params::Validate. For example, Types::Standard
222           provides constraints like "ArrayRef[Int]" (an arrayref of
223           integers), while the closest from Params::Validate is "ARRAYREF",
224           which you'd need to supplement with additional callbacks if you
225           wanted to check that the arrayref contained integers.
226
227           Whatsmore, Type::Params doesn't just work with Types::Standard, but
228           also any other Type::Tiny type constraints.
229
230       Params::ValidationCompiler
231
232       Params::ValidationCompiler does basically the same thing as
233       Type::Params.
234
235       •   Params::ValidationCompiler and Type::Params are likely to perform
236           fairly similarly. In most cases, recent versions of Type::Params
237           seem to be slightly faster, but except in very trivial cases,
238           you're unlikely to notice the speed difference. Speed probably
239           shouldn't be a factor when choosing between them.
240
241       •   Type::Params's syntax is more compact:
242
243              state $check = signature(
244                pos => [
245                  Object,
246                  Optional[Int],
247                  Slurpy[ArrayRef],
248                ],
249              );
250
251           Versus:
252
253              state $check = validation_for(
254                 params => [
255                    { type => Object },
256                    { type => Int,      optional => 1 },
257                    { type => ArrayRef, slurpy => 1 },
258                 ],
259              );
260
261       •   Params::ValidationCompiler probably has slightly better exceptions.
262

NEXT STEPS

264       Here's your next step:
265
266       •   Type::Tiny::Manual::NonOO
267
268           Type::Tiny in non-object-oriented code.
269

AUTHOR

271       Toby Inkster <tobyink@cpan.org>.
272
274       This software is copyright (c) 2013-2014, 2017-2023 by Toby Inkster.
275
276       This is free software; you can redistribute it and/or modify it under
277       the same terms as the Perl 5 programming language system itself.
278

DISCLAIMER OF WARRANTIES

280       THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
281       WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
282       MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
283
284
285
286perl v5.36.0                      2023-01-04     Type::Tiny::Manual::Params(3)
Impressum