xref: /openbsd/usr.sbin/pkg_add/OpenBSD/style.pod (revision b49820e1)
1$OpenBSD: style.pod,v 1.3 2023/09/12 09:01:04 jsg Exp $
2
3=head1 NAME
4
5OpenBSD::style - Perl source file style guide
6
7=head1 DESCRIPTION
8
9This file specifies the preferred style for Perl source files
10in the OpenBSD source tree.
11
12The suggestions in L<style(9)> also apply as far as they make sense
13for Perl code and unless they are overridden in the present manual page.
14
15Just as for L<style(9)>, indentation is an 8 character tab,
16and statements continuing on the next line are indented
17by four more spaces.
18
19Systematically C<use v5.36> or later which yields C<strict>, C<warnings>,
20C<say> and function signatures.
21
22=head2 Subroutines and methods
23
24Prefer object-oriented over procedural style for new code.
25Define a package under either C<OpenBSD::> or C<DPB::>.
26If no state variables are needed, call methods directly on the class name.
27Otherwise, define the state variables as member variables
28and call methods on a constructed object.
29Name the constructor new() unless there are better options.
30
31	my $pkgpath = DPB::PkgPath->new('devel/quirks');
32	say "Normalized version is ", $pkgpath->fullpkgpath;
33
34	$state->errsay(OpenBSD::Temp->last_error);
35
36Inside methods, call the object C<$self> unless there are reasons not to.
37
38Use signatures for every function (except delegations), so that the number
39of parameters can be checked.
40
41	sub m3($self, $p1, $p2)
42	{
43		...
44	}
45
46Accordingly, avoid calling code refs without parentheses, since this creates
47an implicit C<@_> reference.
48
49Note that signatures can also absorb an arbitrary number of parameters with
50C<@l> and set default parameter values like in C++, e.g.
51
52	sub do_backsubst($subst, $string, $unsubst = undef,
53	    $context = 'OpenBSD::PackingElement');
54
55For methods that take no argument apart from the object itself, remove
56trailing parentheses for the method call:
57
58	my $columns = $object->width;
59
60If a function passes on an arbitrary number of arguments
61to another function:
62
63	sub wrapper_method($self, @p)
64	{
65		...
66		do_something_with(@p);
67	}
68
69Anonymous subs should also use signatures
70
71	$state->{opt}{x} =
72	    sub($opt) {
73		push ${$state->{xlist}}, $opt);
74	    };
75
76(Exception: signal handlers are currently not specified and may take an
77arbitrary number of parameters for C<__DIE__> and C<__WARN__>.
78
79Mark the last expression at the end of a function with an explicit
80B<return> unless the function is not intended to return anything,
81or for "constant" methods
82
83	sub isFile($)
84	{
85		1;
86	}
87
88Do not name parameters to methods unless actually used.
89For documentation, use a comment in that case (especially useful
90for base methods)
91
92	# $self->foo($state):
93	# 	explain what foo does
94	sub foo($, $)
95	{
96	}
97
98Avoid using old-style function prototypes unless absolutely necessary
99to create syntax:
100
101	sub try :prototype(&@)
102	{
103		my ($try, $catch) = @_;
104		eval { &$try() };
105		dienow($@, $catch);
106	}
107
108Only use the wantarray() built-in as an optimization;
109it should never change the semantics of the subroutine.
110For example, suppose there is a function returning a list,
111and while the question whether the list is empty sometimes
112needs to be asked, the number of elements never matters.
113Such a function can be structured and used as follows:
114
115	sub get_list
116	{
117		if (wantarray) {
118			# build the complete list and return it
119		} else {
120			# only figure out whether the list is empty
121			# and return 0 if it is or 1 otherwise
122		}
123	}
124
125	if (get_list) {
126		# do something that doesn't need the actual elements
127	}
128
129Let methods that tweak an object return the object itself,
130such that methods can be chained:
131
132	$object->polish->paint('blue')->attach(@decorations);
133
134Since there are no access control restrictions in Perl,
135simply mark internal methods by prefixing their names with C<_>.
136
137Treat anonymous subroutines just like other code,
138indenting them by one tab:
139
140	my $s = sub($self) {
141		...
142		};
143
144When passing an anonymous function as an argument, start it on a new line:
145
146	f($a1, $a2,
147	    sub($self) {
148		...
149		});
150
151=head2 Files and packages
152
153Putting several closely related classes
154into the same source file is fine.
155
156Avoid multiple inheritance unless absolutely necessary
157because it almost always turns into a mess.
158Including some behavior from a different class (mixin)
159is best done on a per-method basis, but explicitly annotate the mixins
160as such.
161
162Delegating from one method of one class to a method of another class,
163passing C<@_> completely unchanged, can be done with the following syntax:
164
165	package Borrower;
166
167	sub visit_notary
168	{
169		&Lender::visit_notary;  # no parentheses here
170	}
171
172This is the only case where a code ref should be called without explicit
173parameters, and where a method can be declared without a prototype.
174
175If a program often uses fork(), set
176
177	$DB::inhibit_exit = 0;
178
179right after each fork() and before the following exec(),
180such that a user trying to debug the main program isn't
181prompted each time one of the child processes exits.
182
183=head2 Data structures
184
185Autovivification is welcome:
186
187	push @{$self->{list}}, $value;
188
189is fine without defining C<$self-E<gt>{list}> first.
190Note that
191
192	if (@{$self->{list}} > 0)
193
194will not autovivify C<$self-E<gt>{list}>,
195so it can be used to check that the list exists and is not empty
196without testing C<if (exists $self-E<gt>{list})> first.
197
198Don't put quotes around hash subscripts unless necessary;
199they are not necessary for simple identifiers that are not keywords.
200Avoid using keywords as hash keys.
201
202Avoid needless arrows in chained lookups.
203Rather than C<$self-E<gt>{a}-E<gt>{b}>, write:
204
205	$self->{a}{b}
206
207=head2 Syntax details
208
209This style guide makes no recommendation to put parentheses
210where they are not required.
211For example, calling built-in or prototyped functions
212does not require parentheses.
213
214Modern Perl operators are preferred.
215Rather than C<defined $value or $value = $something;>
216or C<$value = $something unless defined $value;>, write:
217
218	$value //= $something;
219