Coding Style
Just like human languages, programming languages have a
particular syntax and grammar. If you make a mistake, you end up
with a program that is invalid, or "gibberish." And just as
publishers and periodicals have "house styles" that govern how to
indent paragraphs, how many spaces to put after a period, which
abbreviations to use or avoid, etc., companies and programming
projects also adopt style guidelines.
imaginereadingatextwherenothingwascapitalized,therewasno
spacebetweenwordsandaroundpunctuationmarks,andparagraphswere
separatedbyonlyatinyblankspace.thetextwouldpreserveits
meaning,butbenearlyimpossibletoread. Furthermore, if every article
(or every paragraph) in a magazine adhered to a completely
different style, it would be almost as confusing. Programming is
no different, except that it is far easier to make a syntactically
correct program unreadable by using poor or inconsistent style. Good
style is essential to programming, and a substantial portion of
your homework grade will be based on style.
Programming style generally encompasses how you indent your
code, when you put spaces around operators, and how you name
variables, functions, and classes. There are many opinions about
what constitutes the best style, and most companies and projects
adopt their own guidelines to ensure consistency. In CIS 110,
we generally follow
the textbook's
style guidelines. These are typical of the rules you are
likely to encounter elsewhere, but represent a particular set of
choice among many possibilities. Here are some of the highlights
(where these highlights differ from the booksite's style guide,
follow the highlights):
- Each block of code must be indented 4 spaces to
the right of its parent block. A block is any section of
code enclosed between curly braces ({}). If you use the
introcs installer to set up Dr. Java as part of Homework
0, it will be configured this way automatically. You can
re-indent the current line by pressing TAB. You can
reindent a whole section by selecting it and pressing TAB.
You can reindent the entire file by selecting everything
(Cmd-A on Mac, Ctrl-A on Windows), then hitting TAB. Do
not indent your code manually with spaces, let Dr. Java do
it.
- There is no excuse for improperly indented
code. Ever. Whenever you start typing a new
line of code, press TAB to make sure your cursor is in the
right place. Whenever you cut and paste, or insert code,
select the region around it and press TAB to
reindent. Badly indented code is impossible for humans to
read, and impossible to debug. If Dr. Java
automatically indents your code in a way you don't expect,
you have a bug. Usually you are missing a semi-colon
or curly brace.
- If your code is not properly indented in office
hours, we may refuse to help you. There is no rule
that is more universally agreed upon than the importance
of correct indentation. There is also no single, simple
thing you can do that will help you more than correctly
indenting your code.
- Variable names and function/method names start with
a lower-case letter. If the name is a composite of
multiple words, each subsequent word starts with a capital
letter. For example, "var" is an
acceptable name for a variable, and
"thisIsAVariableName" is also an
acceptable name for a variable. The names
"ThisNameBeginsWithACapitalLetter" and
"this_name_contains_underscores" are not
acceptable for variables in CIS 110.
- The same rules apply to functions and methods
(we introduce functions and methods in the course of the
semester). The first convention, that variable names begin
with a lower-case letter, is very widely accepted. On the
other hand, many projects and companies prefer to separate
words with underscores ("_") rather than using capital
letters.
- As an exception to the above rule, constant variable
names should be all upper-case. Constant variables are
variables whose value never changes. Alternatively, think
of these as symbolic names for particular values. The
canonical example is a variable whose value is
3.14159... This variable would be named
"PI" rather than "pi".
This convention is also widely accepted.
- Class names should begin with a capital letter. If
the name is made up of multiple words, each word should
begin with a capital letter. Once again, this is a widely
accepted convention in object-oriented languages. It is
often difficult to tell from context whether a name refers
to a variable or a class. By following the capitalization
conventions your code becomes much easier to read and
understand.
- Use a single space on either side of mathematical
operators (+, -, *, /). For example, write
"x + y", not
"x+y".
- Put a space before an opening curly brace, or else put
the brace on its own line. Be consistent in your
choice. Put the close curly brace on its own
line.
- Put a space between all function arguments. Example:
use PennDraw.rectangle(0.5, 0.5, 0.25, 0.25). Compare this
to PennDraw.rectangle(0.5,0.5,0.25,0.25). In the second case
it is not easy to read the arguments and see where one ends and
the other begins.
- Do not put a space before the square brackets for an
array. For example, write
"String[] args" and
"args[0]", not
"String [] args" or
"args [0]".
- The spacing around parentheses corresponds to how you
would use them in English and math:
- Put spaces outside the parentheses, but not inside
them, when they are used to group mathematical
computations. For example, write "a + (b +
c)", not "a +(b + c)"
or
"a + ( b + c )".
- Put spaces outside the parentheses, but not inside
them, when they are part of a loop or conditional
(if, for, or while). For
example, write
"if (x > 5) {", not
"if(x > 5){" or
"if ( x > 5 ) {".
- Do not put spaces around parentheses when they are
part of a function call. For example, write
"System.out.println("hello, world.")",
not
"System.out.println ("Hello, world.")"
or
"System.out.println( "Hello, world." )".
Every .java file you submit must start with a file
header comparable to the one below. Often times we will
provide you a template, but you can also cut and paste from
another file or from the example below. Your comment does not
have to be formatted identically to this one, but it must
start with your name, PennKey, and recitation, followed by
instructions for how to run your program, and a
description of what the program does.
/* Name: Benedict Brown
* PennKey: bjbrown
* Recitation: 200
*
* Execution: java HelloWorld
*
* Prints "Hello, World". By tradition, this is everyone's first program.
*
*/
Everyone agrees on the importance of a file header, but
every project and company has its own format. It's common to
include the name of the file, copyright notice, date, and list
of authors at the very top to assert ownership. Some projects
include a list of changes to the file, a list of any other
files the program needs, etc. Depending on the country,
failure to assert copyright at the top of file may implicitly
release it into the public domain. (This was true in the
United States until 1989. Early source code to the UNIX
operating is widely assumed to be in the public domain because
it was distributed without copyright notices before that time.
AT&T famously settled a lawsuit against the University of
California over the UNIX copyrights when this issue came to
light.)
We use the checkstyle program to automatically detect
many (but not all) violations of the textbook's style
guidelines. On most assignments, you will see the output of
checkstyle when you submit the program. If there are any
warnings that we have not specifically told you to
ignore, you should correct them and resubmit or risk a
style deduction. Once we cover the terminal/command prompt, we
will show you how to run checkstyle yourself, before
submitting.