OOP SS14 CodingStyle
OOP SS14 CodingStyle
Dieser Text stammt aus einem Handout fr den Kurs CS106A der Universitt Stanford.
Coding Style
Einfhrung in die objektorientierte Programmierung mit Java SS14 - Florian Echtler/Raphael Wimmer
8. Mai 2014
When writing a paper, you can have well-crafted, correctly spelled sentences and
create A work. Or you can hack out the text in a hurry. It will not look as good,
but it can convey your thoughts and get the job done; its worth maybe a B or a
C. Computer code is not like that. Code that is messy tends to have all sorts of
bugs and other problems. Messy code attracts problems like a half-eaten lollipop
attracts lint. The problems and bugs in poorly written code tend to compound each
other and pile up, so the code ends up nearly worthless. It has bugs. Nobody
knows how to x them or add features without creating more bugs. Once code is in
that state, it is hard to escape. In a sense, code tends to be more either A, or D
or F. Therefore, it is best to write code that is clean to start, and keep it clean as
you add features. This is one of the lessons in CS for successfully building large
projects. For that reason CS 106A emphasizes the habits of clean, well-engineered
code right from the start, building the right habits for the future.
One reason to write clean, well-structured code is that it works better and takes less
time in the end. The other reason to write clean code is that it is just more
satisfying to do a good job on something. Clear, elegant code feels right, just like
any other engineering or artistic creation. Doing it right the rst time is better for
your engineering soul.
Lehrstuhl fr Medieninformatik
Institut fr Information und Medien, Sprache und Kultur
Universitt Regensburg
Readable
One metric for good code is that it reads? nicelythat someone sweeping their
eye over the code can see the algorithmic idea at hand. The original programmer
had an idea in minda way to solve the problem. Does the code communicate that
idea? Writing readable code is important both because it will help any future
reader and because it helps you avoid your own bugs. Bugs, after all, are simply
where the code expresses an idea, but it is not the idea you had in mind. Readable
code has fewer bugs.
Variable names
The rst step in readable code is choosing good names for variables. Typically a
variable gets a noun name that reects what it storeswidth or url or parent. If
you have the number 2, but do not know anything about it, then the generic num is
an okay name. If you know more specically that its a weight or a number of
pixels then the name should reect that knowledge. In Java, the convention is to
begin variables with the rst word lowercase, and uppercase later words like this:
bestScore, remainingCreamPuffs. If you have a pointer to an object but without
any more specic word to use for its variable name, then you can use the name of
the class in lowercase. So if code deals with a Circle or Person object, then obvious
variable names are circle or person. If you know something more specic about the
objects, then more specic names like leftCircle or mother are better. There are a
few idiomatic one-letter namesi, j, k for int loop counters; x, y, z for coordinates.
These are in such wide use that they make very readable code just by familiarity.
Method names
If variables names are the nouns, method names are the verbs. Method names
should reect the action they performremoveAll(), drawLine(), getX(). The
prexes get and set have a typical role. A get method gets a piece of information
from an object, either a value that the object stores or computes: getWidth(),
getNumChildren(). Likewise, set methods typically are used to pass a value in to
an object for it to store or use: setWidth(int width). Methods that return a boolean
are often named starting with is or has.
Whitespace
Use whitespace to help separate the logical parts of the code, in much the same
way that paragraphs separate groups of sentences. Rather than write a block of 20
lines, its nice to put in blank lines to separate the code into its natural 6-line
sections that accomplish logical sub-parts of the computation. Each little section of
code might have a comment to describe what it accomplishes. Likewise, you can
Lehrstuhl fr Medieninformatik
Institut fr Information und Medien, Sprache und Kultur
Universitt Regensburg
use whitespace to show the logical grouping of elements within a line. Do not run
everything together with no spaces. Here are a few examples
1
2
3
4
5
6
7
8
9
10
11
12
13
/* spaces - ok */
if (i * 12 < j) {
14
15
16
Indentation
All programming languages use indentation to show which parts of the code are
owned or controlled by other parts. In CS 106A, whenever there is a {, the code on
the next line should be indentedthis applies to methods, classes, if-statements,
loops, and so on. Eclipse will do this automatically. Hit the tab key to indent one
level manually. You can also select a few lines and use tab to move them all right on
level, and shift-tab to move them all left one level. At the end of the indented code
the matching } should not be indented. In this way, the indented section is visually
set-off from the outer { } that controls it, as shown:
1
2
3
4
5
if (i > 10) {
System . out . println (" i too big ") ;
i = i % 10;
someMethod (i );
}
Lehrstuhl fr Medieninformatik
Institut fr Information und Medien, Sprache und Kultur
Universitt Regensburg
Comments
Comments add the human context to the raw lines of code. They explain the overall
ow and strategy of what is going on. Comments point out assumptions or issues
that affect a part of the program that are not obvious from the code itself.
As you write larger and more complex pieces of code, comments help you keep
track of your own assumptions and ideas, as you scroll around, building and
testing various parts of the code. There gets to be more than you can keep in your
head at one time. The rst step is good variable and method names. They make the
code read well on its own, so fewer comments are required.
Class comments
Each class should have a comment summarizing what it does. Typically the class
comment will mention what sort of data the class encapsulates and what sort of
methods it implements. Professional quality documentation for a class or group of
classes intended for use by others, such as the String class, will also have a few
introductory paragraphs of discussion of what sort of problems the class solves and
what typical client use of the class looks like. For a system of classes, there may be
an architectural overview that summarizes the role of each class and how they all
t together to build the program.
Variable comments
Sometimes the meaning of an instance variable or local variable is completely clear
just from its name. For a complex variable, there is often extra contextual
information about the variable that the code must be consistent about. A comment
where the instance variable is declared is the perfect place to document such
side-issues for the variable: what are its units? Are there constraints on what values
it is allowed to take on? For example, weight might be the perfect name for an
instance variable indicating the weight of the object, but you still need to know, say
for a car simulator, that it is in pounds, or that the weight is for the car but does not
include the passengers or fuel. There is often ancillary information about an
instance variableits meaning, assumptions, and constraintsbeyond what is
captured in its name. The comment for an instance variable can capture this extra
information about the variable in one place.
Method comments
Method comments should describe what the method accomplishes. Emphasize
what the method does for the caller, not how it is implemented. The comment
should describe what the method does to the receiver object, adding in the role of
any parameters. In the standard comment style used with javadoc, the method
Lehrstuhl fr Medieninformatik
Institut fr Information und Medien, Sprache und Kultur
Universitt Regensburg
comment begin with a verb in the third-person singular form (typically ending in
s) describing what the method does. For a complex method, the comment can
address the preconditions that should be true before the method is called, and the
postconditions that will be true after it is done.
1
2
3
4
5
/* Method : removeAll */
/* *
* Removes all the shapes from the window .
*/
public void removeAll () { . . . }
6
7
8
9
10
11
/* Method : addBet */
/* *
* Adds the given bet amount to the pool .
*/
public void addBet ( int bet ) { . . . }
12
13
14
15
16
17
18
/* Method : getCollisionOdds */
/* *
* Returns the odds between 0 and 1 of a collision
* with the specified other craft .
*/
public double getCollisionOdds ( Craft other ) { . . . }
19
20
21
22
23
24
25
26
27
28
/* Method : addCreature */
/* *
* Adds the given creature to the room on which this
* method is invoked . The creature must be valid before
* this method is called . After the call , the Creature
* object will have been updated to show its location as
* the room into which it was placed .
*/
public void addCreature ( Creature creature ) { . . . }