3 RT::StyleGuide - RT Style Guide
7 This file is somewhat out of date; L<hacking> takes precedence over it.
11 All code and documentation that is submitted to be included in the RT
12 distribution should follow the style in this document. This is not to
13 try to stifle your creativity, but to make life easier for everybody who
14 has to work with your code, and to aid those who are not quite sure how
17 These conventions below apply to perl modules, web programs, and
18 command-line programs, specifically, but also might apply to some
19 degree to any Perl code written for use in RT.
21 Note that these are all guidelines, not unbreakable rules. If you have
22 a really good need to break one of the rules herein, however, then it is
23 best to ask on the B<rt-devel> mailing list first.
25 Note that with much of this document, it is not so much the Right Way as
26 it is Our Way. We need to have conventions in order to make life easier
27 for everyone. So don't gripe, and just follow it, because you didn't
28 get a good grade in "Plays Well With Others" in kindergarten and you
29 want to make up for it now.
31 If you have any questions, please ask us on the B<rt-devel> mailing list:
33 http://www.bestpractical.com/rt/lists.html
35 We don't always follow this guide. We are making changes throughout
36 our code to be in line with it. But just because we didn't do
37 it yet, that is no excuse. Do it anyway. :-)
39 This document is subject to change at the whims of the core RT team.
40 We hope to add any significant changes at the bottom of the document.
43 =head1 CODING PRINCIPLES
47 We code everything to perl 5.8.3 or higher. Complete unicode support
48 requires bugfixes found in 5.8.3.
52 All modules will be documented using the POD examples in the module
53 boilerplate. The function, purpose, use of the module will be
54 explained, and each public API will be documented with name,
55 description, inputs, outputs, side effects, etc.
57 If an array or hash reference is returned, document the size of the
58 array (including what each element is, as appropriate) and name each key
59 in the hash. For complex data structures, map out the structure as
60 appropriate (e.g., name each field returned for each column from a DB
61 call; yes, this means you shouldn't use "SELECT *", which you shouldn't
64 Also document what kind of data returned values are. Is it an integer,
65 a block of HTML, a boolean?
67 All command-line program options will be documented using the
68 boilerplate code for command-line programs, which doesn't yet exist.
69 Each available function, switch, etc. should be documented, along
70 with a statement of function, purpose, use of the program. Do not
71 use the same options as another program, for a different purpose.
73 All web templates should be documented with a statement of function,
74 purpose, and use in a mason comment block.
76 Any external documents, and documentation for command-line programs and
77 modules, should be written in POD, where appropriate. From there, they
78 can be translated to many formats with the various pod2* translators.
79 Read the perlpod manpage before writing any POD, because although POD is
80 not difficult, it is not what most people are used to. It is not a
81 regular markup language; it is just a way to make easy documentation
82 for translating to other formats. Read, and understand, the perlpod
83 manpage, and ask us or someone else who knows if you have any questions.
88 Our distribution versions use tuples, where the first number is the
89 major revision, the second number is the version, and third
90 number is the subversion. Odd-numbered versions are development
93 1.0.0 First release of RT 1
94 1.0.1 Second release of RT 1.0
96 1.1.0 First development release of RT 1.2 (or 2.0)
97 2.0.0 First release of RT 2
99 Versions may end in "rc" and a number if they are release candidates:
101 2.0.0rc1 First release candiate for real 2.0.0
106 All code should be self-documenting as much as possible. Only include
107 necessary comments. Use names like "$ticket_count", so you don't need to
113 Include any comments that are, or might be, necessary in order for
114 someone else to understand the code. Sometimes a simple one-line
115 comment is good to explain what the purpose of the following code is
116 for. Sometimes each line needs to be commented because of a complex
117 algorithm. Read Kernighan & Pike's I<Practice of Programming> about
118 commenting. Good stuff, Maynard.
121 =head2 Warnings and Strict
123 All code must compile and run cleanly with "use strict" enabled and the
124 perl "-w" (warnings) option on. If you must do something that -w or
125 strict complains about, there are workarounds, but the chances that you
126 really need to do it that way are remote.
128 =head2 Lexical Variables
130 Use only lexical variables, except for special global variables
131 ($VERSION, %ENV, @ISA, $!, etc.) or very special circumstances (see
132 %HTML::Mason::Commands::session ). Global variables
133 for regular use are never appropriate. When necessary, "declare"
134 globals with "use vars" or "our()".
136 A lexical variable is created with my(). A global variable is
137 pre-existing (if it is a special variable), or it pops into existence
138 when it is used. local() is used to tell perl to assign a temporary
139 value to a variable. This should only be used with special variables,
140 like $/, or in special circumstances. If you must assign to any global
141 variable, consider whether or not you should use local().
143 local() may also be used on elements of arrays and hashes, though there
144 is seldom a need to do it, and you shouldn't.
147 =head2 Pass by Reference
149 Arrays and hashes should be passed to and from functions by reference
150 only. Note that a list and an array are NOT the same thing. This
153 return($user, $form, $constants);
155 An exception might be a temporary array of discrete arguments:
157 my @return = ($user, $form);
158 push @return, $constants if $flag;
161 Although, usually, this is better (faster, easier to read, etc.):
164 return($user, $form, $constants);
166 return($user, $form);
169 We need to talk about Class::ReturnValue here.
172 =head2 Method parameters
174 If a method takes exactly one mandatory argument, the argument should be
175 passed in a straightforward manner:
180 In all other cases, the method needs to take named parameters, usually
181 using a C<%args> hash to store them:
186 Description => undef,
190 You may specify defaults to those named parameters instead of using
191 C<undef> above, as long as it is documented as such.
193 It is worth noting that the existing RT codebase had not followed this
194 style perfectly; we are trying to fix it without breaking existing APIs.
198 Modules should provide test code, with documentation on how to use
199 it. Test::More makes it easy to create tests. Any code you write
200 should have a testsuite. Any code you alter should have a test
201 suite. If a patch comes in without tests, there is something wrong.
203 When altering code, you must run the test harness before submitting a
204 patch or committing code to the repository.
206 "make test" will run the test suite.
210 Always report errors using $RT::Logger. It's a Log::Dispatch object.
211 Unlike message meant for the user, log messages are not to be
214 There are several different levels ($RT::Logger methods) of logging:
220 Used for messages only needed during system debugging.
224 Should be used to describe "system-critical" events which aren't errors.
225 Examples: creating users, deleting users, creating tickets, creating queues,
226 sending email (message id, time, recipients), recieving mail, changing
227 passwords, changing access control, superuser logins)
231 Used for RT-generated failures during execution.
235 Should be used for messages when an action can not be completed due to some
236 error condition beyond our control.
240 In the web UI and modules, never print directly to STDERR. Do not print
241 directly to STDOUT, unless you need to print directly to the user's console.
243 In command-line programs, feel free to print to STDERR and STDOUT as
244 needed for direct console communication. But for actual error reporting,
250 Always check return values from system calls, including open(),
251 close(), mkdir(), or anything else that talks directly to the system.
252 Perl built-in system calls return the error in $!; some functions in
253 modules might return an error in $@ or some other way, so read the module's
254 documentation if you don't know. Always do something, even if it is
255 just calling $RT::Logger->warning(), when the return value is not what you'd expect.
261 Much of the style section is taken from the perlsyle manpage. We make
262 some changes to it here, but it wouldn't be a bad idea to read that
269 =item function vs. sub(routine) vs. method
271 Just because it is the Perl Way (not necessarily right for all
272 languages, but the documented terminology in the perl documentation),
273 "method" should be used only to refer to a subroutine that are object
274 methods or class methods; that is, these are functions that are used
275 with OOP that always take either an object or a class as the first
276 argument. Regular subroutines, ones that are not object or class
277 methods, are functions. Class methods that create and return an object
278 are optionally called constructors.
282 "users" are normally users of RT, the ones hitting the site; if using
283 it in any other context, specify.
284 "system users" are user
285 names on the operating system. "database users" are the user names in
286 the database server. None of these needs to be capitalized.
293 Don't use single-character variables, except as iterator variables.
295 Don't use two-character variables just to spite us over the above rule.
297 Constants are in all caps; these are variables whose value will I<never>
298 change during the course of the program.
300 $Minimum = 10; # wrong
301 $MAXIMUM = 50; # right
303 Other variables are lowercase, with underscores separating the words.
304 They words used should, in general, form a noun (usually singular),
305 unless the variable is a flag used to denote some action that should be
306 taken, in which case they should be verbs (or gerunds, as appropriate)
307 describing that action.
309 $thisVar = 'foo'; # wrong
310 $this_var = 'foo'; # right
311 $work_hard = 1; # right, verb, boolean flag
312 $running_fast = 0; # right, gerund, boolean flag
314 Arrays and hashes should be plural nouns, whether as regular arrays and
315 hashes or array and hash references. Do not name references with "ref"
316 or the data type in the name.
318 @stories = (1, 2, 3); # right
319 $comment_ref = [4, 5, 6]; # wrong
320 $comments = [4, 5, 6]; # right
321 $comment = $comments->[0]; # right
323 Make the name descriptive. Don't use variables like "$sc" when you
324 could call it "$story_count". See L<"Comments">.
326 There are several variables in RT that are used throughout the code,
327 that you should use in your code. Do not use these variable names for
328 anything other than how they are normally used, and do not use any
329 other variable names in their place. Some of these are:
331 $self # first named argument in object method
333 Subroutines (except for special cases, like AUTOLOAD and simple accessors)
334 begin with a verb, with words following to complete the action. Accessors
335 don't start with "Get" if they're just the name of the attribute.
337 Accessors which return an object should end with the suffix Obj.
339 This section needs clarification for RT.
341 Words begin with a capital letter. They
342 should as clearly as possible describe the activity to be peformed, and
343 the data to be returned.
351 Subroutines beginning with C<_> are special: they are not to be used
352 outside the current object. There is not to be enforced by the code
353 itself, but by someone very big and very scary.
355 For large for() loops, do not use $_, but name the variable.
356 Do not use $_ (or assume it) except for when it is absolutely
357 clear what is going on, or when it is required (such as with
361 print; # OK; everyone knows this one
362 print uc; # wrong; few people know this
363 print uc $_; # better
366 Note that the special variable C<_> I<should> be used when possible.
367 It is a placeholder that can be passed to stat() and the file test
368 operators, that saves perl a trip to re-stat the file. In the
369 example below, using C<$file> over for each file test, instead of
370 C<_> for subsequent uses, is a performance hit. You should be
371 careful that the last-tested file is what you think it is, though.
373 if (-d $file) { # $file is a directory
375 } elsif (-l _) { # $file is a symlink
379 Package names begin with a capital letter in each word, followed by
380 lower case letters (for the most part). Multiple words should be StudlyCapped.
383 RT::Database::MySQL # proper name
384 RT::Display::Provider # good
385 RT::CustomField # not so good, but OK
387 Plugin modules should begin with "RT::Extension::", followed by the name
390 =head1 Code formatting
392 When in doubt, use perltidy; RT includes a F<.perltidyrc>.
394 =head2 Indents and Blank Space
396 All indents should be four spaces; hard tabs are forbidden.
398 No space before a semicolon that closes a statement.
403 Line up corresponding items vertically.
409 open(FILE, $fh) or die $!;
410 open(FILE2, $fh2) or die $!;
412 $rot13 =~ tr[abcedfghijklmnopqrstuvwxyz]
413 [nopqrstuvwxyzabcdefghijklm];
415 # note we use a-mn-z instead of a-z,
420 Put blank lines between groups of code that do different things. Put
421 blank lines after your variable declarations. Put a blank line before a
422 final return() statement. Put a blank line following a block (and
423 before, with the exception of comment lines).
427 # this is my function!
430 my $obj = new Constructor;
444 For control structures, there is a space between the keyword and opening
445 parenthesis. For functions, there is not.
453 Be careful about list vs. scalar context with parentheses!
455 my @array = ('a', 'b', 'c');
456 my($first_element) = @array; # a
457 my($first_element) = ('a', 'b', 'c'); # a
458 my $element_count = @array; # 3
459 my $last_element = ('a', 'b', 'c'); # c
461 Always include parentheses after functions, even if there are no arguments.
462 There are some exceptions, such as list operators (like print) and unary
463 operators (like undef, delete, uc).
465 There is no space inside the parentheses, unless it is needed for
468 for ( map { [ $_, 1 ] } @list ) # OK
469 for ( @list ) # not really OK, not horrible
471 On multi-line expressions, match up the closing parenthesis with either
472 the opening statement, or the opening parenthesis, whichever works best.
480 if ($foo && $bar && $baz
485 Whether or not there is space following a closing parenthesis is
486 dependent on what it is that follows.
488 print foo(@bar), baz(@buz) if $xyzzy;
490 Note also that parentheses around single-statement control expressions,
491 as in C<if $xyzzy>, are optional (and discouraged) C<if> it is I<absolutely>
492 clear -- to a programmer -- what is going on. There is absolutely no
493 need for parentheses around C<$xyzzy> above, so leaving them out enhances
494 readability. Use your best discretion. Better to include them, if
495 there is any question.
497 The same essentially goes for perl's built-in functions, when there is
498 nothing confusing about what is going on (for example, there is only one
499 function call in the statement, or the function call is separated by a
500 flow control operator). User-supplied functions must always include
503 print 1, 2, 3; # good
504 delete $hash{key} if isAnon($uid); # good
507 However, if there is any possible confusion at all, then include the
508 parentheses. Remember the words of Larry Wall in the perlstyle manpage:
510 When in doubt, parenthesize. At the very least it will
511 let some poor schmuck bounce on the % key in vi.
513 Even if you aren't in doubt, consider the mental welfare
514 of the person who has to maintain the code after you, and
515 who will probably put parens in the wrong place.
517 So leave them out when it is absoutely clear to a programmer, but if
518 there is any question, leave them in.
523 (This is about control braces, not hash/data structure braces.)
525 There is always a space befor the opening brace.
527 while (<$fh>){ # wrong
528 while (<$fh>) { # right
530 A one-line block may be put on one line, and the semicolon may be
533 for (@list) { print }
535 Otherwise, finish each statement with a semicolon, put the keyword and
536 opening curly on the first line, and the ending curly lined up with the
544 Generally, we prefer "cuddled elses":
554 Put space around most operators. The primary exception is the for
555 aesthetics; e.g., sometimes the space around "**" is ommitted,
556 and there is never a space before a ",", but always after.
558 print $x , $y; # wrong
559 print $x, $y; # right
564 Note that "&&" and "||" have a higher precedence than "and" and "or".
565 Other than that, they are exactly the same. It is best to use the lower
566 precedence version for control, and the higher for testing/returning
569 $bool = $flag1 or $flag2; # WRONG (doesn't work)
570 $value = $foo || $bar; # right
571 open(FILE, $file) or die $!;
573 $true = foo($bar) && baz($buz);
574 foo($bar) and baz($buz);
576 Note that "and" is seldom ever used, because the statement above is
577 better written using "if":
579 baz($buz) if foo($bar);
581 Most of the time, the confusion between and/&&, or/|| can be alleviated
582 by using parentheses. If you want to leave off the parentheses then you
583 I<must> use the proper operator. But if you use parentheses -- and
584 normally, you should, if there is any question at all -- then it doesn't
585 matter which you use. Use whichever is most readable and aesthetically
586 pleasing to you at the time, and be consistent within your block of code.
588 Break long lines AFTER operators, except for ".", "and", "or", "&&", "||".
589 Try to keep the two parts to a binary operator (an operator that
590 has two operands) together when possible.
592 print "foo" . "bar" . "baz" .
595 print "foo" . "bar" . "baz"
598 print $foo unless $x == 3 && $y ==
599 4 && $z == 5; # wrong
601 print $foo unless $x == 3 && $y == 4
607 Put space around a complex subscript inside the brackets or braces.
609 $foo{$bar{baz}{buz}}; # OK
610 $foo{ $bar{baz}{buz} }; # better
612 In general, use single-quotes around literals, and double-quotes
613 when the text needs to be interpolated.
615 It is OK to omit quotes around names in braces and when using
616 the => operator, but be careful not to use a name that doubles as
617 a function; in that case, quote.
619 $what{'time'}{it}{is} = time();
621 When making compound statements, put the primary action first.
623 open(FILE, $fh) or die $!; # right
624 die $! unless open(FILE, $fh); # wrong
626 print "Starting\n" if $verbose; # right
627 $verbose && print "Starting\n"; # wrong
630 Use here-docs instead of repeated print statements.
633 This is a whole bunch of text.
634 I like it. I don't need to worry about messing
635 with lots of print statements and lining them up.
638 Just remember that unless you put single quotes around your here-doc
639 token (<<'EOT'), the text will be interpolated, so escape any "$" or "@"
642 =head1 INTERNATIONALIZATION
645 =head2 String extraction styleguide
651 Templates should use the /l filtering component to call the localisation
656 Should become <&|/l&>Foo!</&>
658 All newlines should be removed from localized strings, to make it easy to
659 grep the codebase for strings to be localized
665 Should become <&|/l&>Foo Bar Baz</&>
668 Variable subsititutions should be moved to Locale::MakeText format
670 The string Hello, <%$name %>
672 should become <&|/l, $name &>Hello, [_1]</&>
675 Multiple variables work just like single variables
677 The string You found <%$num%> tickets in queue <%$queue%>
679 should become <&|/l, $num, $queue &>You found [_1] tickets in queue [_2]</&>
681 When subcomponents are called in the middle of a phrase, they need to be escaped
684 The string <input type="submit" value="New ticket in"> <& /Elements/SelectNewTicketQueue&>
686 should become <&|/l, $m->scomp('/Elements/SelectNewTicketQueue')&><input type="submit" value="New ticket in"> [_1]</&>
691 The string <& /Elements/TitleBoxStart, width=> "40%", titleright => "RT $RT::VERSION for RT->Config->Get('rtname')", title => 'Login' &>
693 should become <& /Elements/TitleBoxStart,
695 titleright => loc("RT [_1] for [_2]",$RT::VERSION, RT->Config->Get('rtname')),
696 title => loc('Login'),
703 Within RT's core code, every module has a localization handle available through the 'loc' method:
705 The code return ( $id, "Queue created" );
707 should become return ( $id, $self->loc("Queue created") );
709 When returning or localizing a single string, the "extra" set of parenthesis () should be omitted.
711 The code return ("Subject changed to ". $self->Data );
713 should become return $self->loc( "Subject changed to [_1]", $self->Data );
716 It is important not to localize the names of rights or statuses within RT's core, as there is logic that depends on them as string identifiers. The proper place to localize these values is when they're presented for display in the web or commandline interfaces.
721 =head1 CODING PRCEDURE
723 This is for new programs, modules, specific APIs, or anything else.
727 =item Present idea to rt-devel
729 We may know of a better way to approach the problem, or know of an
730 existing way to deal with it, or know someone else is working on it.
731 This is mostly informal, but a fairly complete explanation for the need
732 and use of the code should be provided.
735 =item Present complete specs to rt-devel
737 The complete proposed API should be submitted for
738 approval and discussion. For web and command-line programs, present the
739 functionality and interface (op codes, command-lin switches, etc.).
741 The best way to do this is to take the documentation portion of the
742 boilerplate and fill it in. You can make changes later if necessary,
743 but fill it in as much as you can.
747 =item Prepare for code review
749 When you are done, the code will undergo a code review by a member of
750 the core team, or someone picked by the core team. This is not to
751 belittle you (that's just a nice side effect), it is to make sure that
752 you understand your code, that we understand your code, that it won't
753 break other code, that it follows the documentation and existing
754 proposal. It is to check for possible optimizations or better ways of
757 Note that all code is expected to follow the coding principles and style
758 guide contained in this document.
763 After the code is done (possibly going through multiple code reviews),
764 if you do not have repository access, submit it to rt-bugs@fsck.com as a
765 unified diff. From that point on, it'll be handled by someone with
771 =head1 BUG REPORTS, PATCHES
773 Use rt-bugs@bestpractical.com for I<any> bug that is not being fixed
774 immediately. If it is not in RT, there is a good chance it will not be
777 Send patches to rt-bugs@bestpractical.com, too. Use C<diff -u> for
782 RT uses a convention to denote the foreign key status in its tables.
783 The rule of thumb is:
787 =item When it references to another table, always use the table name
789 For example, the C<Template> field in the C<Scrips> table refers to
790 the C<Id> of the same-named C<Template> table.
792 =item Otherwise, always use the C<Id> suffix
794 For example, the C<ObjectId> field in the C<ACL> table can refer
795 to any object, so it has the C<Id> suffix.
799 There are some legacy fields that did not follow this rule, namely
800 C<ACL.PrincipalId>, C<GroupMembers.GroupId> and C<Attachments.TransactionId>,
801 but new tables are expected to be consistent.
804 =head1 EXTENDING RT CLASSES
806 =head2 The Overlay mechanism
808 RT's classes allow "overlay" methods to be placed into files named Filename_Vendor.pm and Filename_Local.pm
809 _Vendor is for 3rd-party vendor add-ons, while _Local is for site-local customizations.
811 These overlay files can contain new subs or subs to replace existing subs in this module.
813 Each of these files should begin with the line
815 no warnings qw(redefine);
817 so that perl does not kick and scream when you redefine a subroutine or variable in your overlay.
821 Talk about DBIx::SearchBuilder
825 cascading style sheets
827 Talk about adding a new translation
829 Talk more about logging