3.27.CodingStandard: coding_standards.tex

File coding_standards.tex, 13.7 KB (added by jelinson, 2 years ago)
Line 
1\documentclass[pdftex,12pt]{article}
2
3\usepackage[usenames,dvipsnames]{color}
4\usepackage[margin=1in]{geometry}
5\usepackage[pdftex]{graphicx}
6\usepackage[T1]{fontenc}
7\usepackage{amsmath}
8\usepackage{amsthm}
9\usepackage{amsfonts}
10\usepackage{amssymb}
11\usepackage{verbatim}
12\usepackage{mathpazo}
13\usepackage{xfrac}
14\usepackage{ushort}
15\usepackage{fancyvrb,fancybox,calc} 
16\usepackage[svgnames]{xcolor} 
17\usepackage{algorithmic}
18\usepackage{longtable}
19\usepackage{algorithm}
20\usepackage{hyperref}
21
22\setlength{\parindent}{0pt}
23
24\newcommand{\block}{\mathbb}
25\newcommand{\script}{\mathcal}
26\newcommand{\fancy}{\mathfrak}
27\newcommand{\C}{\block{C}}
28\newcommand{\R}{\block{R}}
29\newcommand{\Z}{\block{Z}}
30\newcommand{\Q}{\block{Q}}
31\newcommand{\N}{\block{N}}
32\newcommand{\I}{^{-1}}
33\newcommand{\set}[2]{\{#1|#2\}}
34\newcommand{\topic}[1]{\noindent{\textbf{#1}}}
35\newcommand{\bij}{\longleftrightarrow}
36\newcommand{\bslash}{\setminus}
37\newcommand{\cl}[1]{\overline{#1}}
38\newcommand{\seq}{\subseteq}
39\newcommand{\ds}{\displaystyle}
40\newcommand{\Wlog}{Without loss of generality }
41\newcommand{\rp}{$(\Rightarrow)$ }
42\newcommand{\lp}{$(\Leftarrow)$ }
43\newcommand{\cbox}[2]{\fcolorbox{#1}{white}{#2}}
44\newcommand{\into}{\ds\bar{\int}}
45\newcommand{\intu}{\ds\ushort{\int}}
46\newcommand{\tx}[1]{\text{#1}}
47
48\renewcommand{\qedsymbol}{\tiny$\blacksquare$}
49\renewcommand{\labelenumi}{(\alph{enumi})}
50
51\newtheorem{thm}{Theorem}
52\newtheorem{prop}[thm]{Proposition}
53\newtheorem{cor}[thm]{Corollary}
54\newtheorem{lem}[thm]{Lemma}
55
56\theoremstyle{definition}
57\newtheorem{defn}{Definition}
58\newtheorem{ex}{Example}
59\newtheorem{nex}[ex]{Non-Example}
60
61\theoremstyle{remark}
62\newtheorem*{rec}{Recall}
63\newtheorem*{rem}{Remark}
64\newtheorem*{note}{Note}
65\newtheorem*{notate}{Notation}
66\newtheorem*{idea}{Idea}
67\newtheorem*{question}{Question}
68
69\DeclareMathOperator*{\mesh}{mesh}
70\definecolor{biege}{rgb}{.92,.92,.92}
71
72\newenvironment{verbcode}{\VerbatimEnvironment%
73  \noindent
74        %{\columnwidth-\leftmargin-\rightmargin-2\fboxsep-2\fboxrule-4pt}
75  \begin{Sbox} 
76  \begin{minipage}{\linewidth-2\fboxsep-2\fboxrule-4pt}   
77  \scriptsize
78  \begin{Verbatim}[gobble=2, numbers=right]
79}{%
80  \end{Verbatim} 
81  \end{minipage}   
82  \end{Sbox} 
83  \fcolorbox{black}{biege}{\TheSbox} 
84} 
85
86\begin{document}
87
88%%%%%%%%%%%%%
89%\setlength{\topmargin}{-.9in}
90\newcommand{\HRule}{\rule{\linewidth}{0.4mm}}
91\begin{center}
92\HRule \\
93\textsc{Erin Coughlan, Julius Elinson, Michael Morton, Rebecca Thomas}\\[.1cm]
94\textsc{\Large{Coding Standard}}\\[-.1cm] % Title
95\HRule \\[.4cm]
96\end{center}
97%%%%%%%%%%%%%
98Our coding standard is modeled after the PEP 8 Python standard. Since we do differ in several places intentionally, we enumerate our entire coding policy here. While these enumerations demonstrate the specifics, included at the end is an example file that adheres to all our of coding standards for demonstration.
99\subsection*{Code Layout}
100\begin{center}
101 \begin{tabular}{| p{3.5cm}  | p{12cm} |} 
102 \hline
103 Property & Description \\
104 \hline
105 Indentation size & 4 spaces for each nested scope \\
106 \hline
107 \raggedright Using tabs vs. spaces & exclusively spaces\\
108 \hline
109 Max line length & 79 characters\\
110 \hline 
111 Using blank lines & single blank lines delimit class methods; single blank lines separate class docstrings and the constructor; single blank lines are also used within functions to meaningfully separate blocks of code; single blank lines are used in between header comment of files and imports and two blank lines are used before the start of code\\
112 \hline 
113 
114 
115\end{tabular}
116\end{center}
117\subsection*{Comments}
118\begin{center}
119 \begin{tabular}{| p{3.5cm}  | p{12cm} |} 
120 \hline
121 Property & Description \\
122 \hline
123 When to include & comments are used in the following contexts: headers of all files, all class and function declarations, within tricky/non-obvious functions and to explain what certain constants are used for\\
124 \hline
125 What to include & header comments of files include the creation date, the author (TechTrek), and the file's name; docstrings for classes explain the primary function of the class; docstrings for methods explain what the function does, specifies the types of the input parameters, as well as the return type \\
126 \hline
127 Block comments & block comments are used for docstrings, in locations specified above \\
128 \hline
129 \raggedright Single line comments & single line comments explain the reasoning for any single line or block of code that immediately follows (no blank line in between); these comments explain the purpose for the code, rather than just say what it does\\
130 \hline
131 Trailing comments & not used \\ 
132 \hline
133 \raggedright End-of-line comments & used sparingly to acknowledge temporary code that will be replaced or intentionally incomplete implementations\\
134 \hline
135 \end{tabular}
136\end{center}
137\subsection*{Declarations}
138\begin{center}
139\begin{tabular}{| p{3.5cm} | p{12cm} |} 
140 \hline
141 Property & Description \\
142 \hline
143 Number per line & always 1 \\
144 \hline
145 Initialization & initializations of objects that are function arguments are made and declared before handing them to the function\\
146 \hline
147 Placement & any local variables are defined at the start of the logical block where it first appears if its value can be set, otherwise it is declared when its value is available; declarations of local variables are used instead of handing them directly to function parameters\\
148 \hline
149\end{tabular}
150\end{center}
151\subsection*{Naming Conventions}
152\begin{center}
153\begin{tabular}{| p{3.5cm} | p{12cm} |} 
154 \hline
155 Property & Description \\
156 \hline
157 Descriptive names & names should be concise and informative; avoid use of the following words in variable/function names: type, object, class, kind, variable, or generally an object's class\\
158 \hline
159 Name lengths & names should almost never be longer than 10 or 12 characters and no shorter than 4 characters (with the exception of counters/indices)\\
160 \hline
161 Capitalization & see the chart below for capitalization policy of various elements \\
162 \hline
163 Variable names & should be clear and concise; should not be named after the expected value of the variable\\
164 \hline
165 Method names & getters and setters follow the basic \verb+getValue()+ \verb+setValue()+ format; boolean checkers are of the form \verb+isProperty()+ where the true result corresponds to \verb+property+ being true; in general, method names should indicate what it does (if this cannot be articulated then it isn't a useful/good method)\\
166 \hline
167 Constant names & can use standard abbreviations like \verb+IMG+ for image and \verb+SM+, \verb+MD+, and \verb+LG+ for small, medium and large, respectively; the names should be very specific to avoid confusion and clashes\\
168\hline
169Class names & indicate their purpose/function; these can push the 12 character limit if the class is very specific as a result of abstraction; prefixes/starts of class names should be distinct for best clarity, i.e. avoid using both \verb+BuildPowerEntry+ and \verb+BuildPowerMenu+\\
170\hline
171Other name rules & due to their frequency throughout our code, the keywords \verb+build+ and \verb+research+ are abbreviated \verb+bld+ and \verb+rsrch+ and are always prefixes when they appear in an element name; the same applies for power, material and transportation as \verb+pow+, \verb+mat+, and \verb+trans+; if object type must be part of a variable name, it must be a suffix\\
172\hline
173Abbreviations & in addition to the abbreviations indicated above, general abbreviations truncate the word to the first (or in rare cases second) syllable; abbreviations must be obvious; abbreviations are not put in all caps unless that element is already as such\\
174\hline
175Loop indices & \verb+i+ then \verb+j+ for integers; object type or similar for other index types\\
176\hline
177\end{tabular}
178\end{center}
179For capitalization conventions, we adhere to the following standards:
180\begin{center}
181\begin{tabular}{| l | l |}
182 \hline
183 Element  & Style \\
184  \hline
185\hline
186 file & \verb+camelCaps+ \\ 
187  \hline
188  class & \verb+CamelCaps+ \\ 
189 \hline
190  data member & \verb+camelCaps+ \\ 
191 \hline
192  function & \verb+camelCaps+ \\ 
193  \hline
194  function parameter & \verb+camelCaps+ \\ 
195 \hline
196  constants & \verb+ALL_CAPS+ \\ 
197 \hline
198\end{tabular}
199\end{center}
200\subsection*{Statement Formatting}
201\begin{center}
202\begin{tabular}{| p{3.5cm}  | p{12cm} |} 
203 \hline
204 Property & Description \\
205 \hline
206 Simple statements & spaces around operators, after commas, not after parentheses, brackets or braces; one statement per line \\
207 \hline
208 \raggedright Compound statements & broken-up if possible by evaluating smaller parts and using local variables\\
209 \hline
210 Return statements & on their own line; no code follows them within the same scope\\
211 \hline
212 If statements & most common case listed first; never use \verb+if var is True:+ since \verb+if var:+ would suffice; use new line for case code \\
213 \hline
214 For statements & use new line for iteration code; use \verb+i+ or \verb+j+ for looping over integer lists, or nested integers lists; otherwise, use simple, descriptive name of object type or what the list consists of \\
215 \hline
216 While statements & use new line for iteration code\\
217 \hline
218 Switch statements & N/A\\
219 \hline
220  \raggedright Try-catch statements & use else case; use try/except control flow for any file IO, when taking input directly from the user, and any arithmetic involving division; all operations after the risk-prone operation(s) should be done in the else case\\
221 \hline
222 Parentheses & used only when necessary for correct operator associativity; parenthesis with a comma become tuples, which is what is used for function pointers that are callable\\
223 \hline
224\end{tabular}
225\end{center}
226\subsection*{Methods}
227\begin{center}
228\begin{longtable}{| p{3.5cm}  | p{12cm} |} 
229 \hline
230 Property & Description \\
231 \hline
232 Length & methods should be limited to approximately 20-40 lines; there should be no more than three levels of nested scope within a method\\
233 \hline
234\raggedright Parameter list lengths & methods generally should not have more than 4 parameters and never more than 6\\
235\hline
236\raggedright Parameter list order & parameters should be prioritized by importance/likelihood of changing so that default values can be assigned to trailing parameters; if position is ever an argument, it goes first; with inheritance, constructors should use the same leading parameters as the base class, with trailing ones reserved for derived classes\\
237\hline
238 \end{longtable}
239\end{center}
240\subsection*{Exception and Error Handling}
241\begin{center}
242\begin{tabular}{| p{3.5cm}  | p{12cm} |} 
243 \hline
244 Property & Description \\
245 \hline
246 When & all file IO, all user input, all arithmetic with division \\
247 \hline
248 Where & at the level closest to the risk-prone operation; \verb+fileio.py+ handles the file IO error handling \\
249 \hline 
250 How & define routines to address expected errors; write to a log file if unresolvable so user can try to troubleshoot\\
251 \hline
252\end{tabular}
253\end{center}
254\subsection*{Miscellany}
255\begin{center}
256\begin{tabular}{| p{3.5cm}  | p{12cm} |} 
257 \hline
258 Property & Description \\
259 \hline
260 Imports & Python imports are listed in the following order: standard library modules, third-party modules and lastly local modules; \verb+from <module> import *+ is avoided, except for importing constants, in which case generally \verb+__all__+ will be used to enumerate what precisely is to be imported\\
261 \hline
262 \raggedright Other types of comments  & occasionally a single line consisting of many hash symbols with centered text in between them is used to separate large blocks of code\\
263 \hline
264 File distribution & files are organized into \verb+\src+ and \verb+\resource+ directories, which contain source code and game data, respectively; each source file has at most one class.\\
265 \hline
266 Globals & global constants are used for dimensions, directory paths, colors, and other static values; no global variables are used\\
267 \hline
268 Output & output to the console from the program is controlled by a constant called \verb+DEBUG+; all print statements are preceded by a check for this constants value; in the actual release this value will simply be set to false and no output will be produced\\
269 \hline
270 \end{tabular}
271\end{center}
272\subsection*{Sample File}
273\begin{verbcode}
274```
275image.py
276
277created on Feb 11, 2012
278@author: TechTrek
279'''
280
281import pygame
282from rectangle import Rectangle
283
284
285class Image:
286    """ wrapper for pygame.Image that stores all information needed to
287        render """
288
289    def __init__(self, pos, width, height, image):
290        """
291            initialize data members
292
293            input type: (int, int), int, int, pygame.Image
294        """
295        self.image = pygame.transform.smoothscale(image, (width, height))
296        self.pos = (self.left, self.top) = pos
297        self.width = width
298        self.height = height
299
300    def render(self, surface):
301        """
302            draw image to surface
303
304            input type: pygame.Surface
305            return type: None
306        """
307        surface.blit(self.image, pygame.Rect(self.left, self.top,
308                                             self.width, self.height))
309
310    def getRect(self):
311        """
312            create rectangle from image (used in collisions)
313
314            input type: None
315            return type: pygame.Rectangle
316        """
317        wrapperRect = Rectangle(self.pos, self.width, self.height)
318        return wrappRect.getRect()
319
320    def resize(self, xScale, yScale):
321        """
322            resize image based new scale
323
324            input type: (int, int)
325            return type: None
326        """
327        self.left = int(self.origPos[0] * xScale)
328        self.top = int(self.origPos[1] * yScale)
329        self.pos = (self.left, self.top)
330        self.width = int(self.origWidth * xScale)
331        self.height = int(self.origHeight * yScale)
332        self.image = pygame.transform.smoothscale(self.origImage,
333                                                  (self.width, self.height))
334
335\end{verbcode}
336\end{document}