CS 21a Lecture Slides

Download Report

Transcript CS 21a Lecture Slides

Formatting Code in Java
Common Conventions
and “Luis’s Pet Peeves”
(Originally given as a lecture in CS 21a at Ateneo
de Manila University. See last slide for updates.)
Why is Good Format important?


Your code needs to be readable!
Others need to be able to read and understand
your code easily


helps others fix and maintain your code in the future
You need to be able to read your code too!



avoid syntax errors
readability helps debugging
future maintenance

CS 21a
7/26/02
it’s easy to forget how your own code works!
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 2
Formatting Conventions


Formatting conventions ensures
consistency and therefore, familiarity for
readers
Sun’s Coding Conventions for Java





CS 21a
7/26/02
http://java.sun.com/docs/codeconv/
formatting convention that Sun follows in all
its code and books
lots of other people follow it too
READ IT!
generally good, except for Luis’ Pet Peeves
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 3
Identifier names

Class names start upper-cased


Variable and Method names start lower-cased




e.g., BankAccount, Vehicle, VehicleApplet
e.g., aliceAccount, hondaCivic
Words within name are capitalized
Words within name are not separated by spaces
or underscores
Constants (more later) are ALL_CAPS and
words in name are separated by an underscore

CS 21a
7/26/02
e.g., PI, MAX_WIDTH, DEFAULT_WIDTH
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 4
Choosing Names


In general use descriptive names
Try to be succint, but don’t skimp too much, and
avoid “skppng vwls” (especially for class names)


In some cases, OK to use 1-or-2 letter names




e.g., use BankAccount instead of BnkAccnt
only for temporary and short-use parameters or
local variables (not for fields)
i, j, k are common in for statements
also you can do boolean b, int n, double d, float f,
etc. or BankAccount ba, GarbageTruck gb, etc.
Always use descriptive names for fields and
methods
CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 5
Comments

Block-style comments
/*
* This is a multi-line comment.
* Use when you need to write a long comment about a fragment
*/

One-line comments

/* C-style comments */


use to put descriptive notes before a code fragment
// C++ style comment

use at the end of the line



usually to describe variables or short pieces of code
also use for commenting-out code
javadoc comments


CS 21a
7/26/02
like block-style, but starts with /** instead
use immediately before classes, methods, and fields
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 6
Indentation

Indent when starting out new blocks of code






after public class MyClass {
after public int myMethod() {
after an if ( myCondition ) {
after an else {
after a for, while, or do
Align the if statement, the {, and the }
if ( myCondition )
{
x = x + 1;
}

Sun says indent 4 spaces

CS 21a
7/26/02
but if you’re strapped for space, 2 or 3 will do
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 7
Indentation Example
public class CheckIfLarge
{
public static void main( String args[] )
{
int num;
num = Input.readInt();
if (num > 100)
System.out.println(“Number is large”);
System.out.println(“Thanks”); //executed unconditionally
}
Wrong!
}
CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 8
Indentation Example
public class CheckIfLarge
{
public static void main( String args[] )
{
int num;
num = Input.readInt();
if (num > 100)
System.out.println(“Number is large”);
System.out.println(“Thanks”); //executed unconditionally
}
Wrong!
}
CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 9
Indentation Example
public class CheckIfLarge
{
public static void main( String args[] )
{
int num;
num = Input.readInt();
if (num > 100)
System.out.println(“Number is large”);
System.out.println(“Thanks”); //executed unconditionally
}
OK
}
CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 10
Wrapping Lines






Wrap when line becomes > 70 characters
Break after a comma.
Break before an operator.
Prefer higher-level breaks to lower-level breaks.
Align the new line with the beginning of the expression
at the same level on the previous line.
If the above rules lead to confusing code or to code
that's squished up against the right margin, just use
two indents (if using Sun style) or one indent (if using
Luis style) instead.

CS 21a
7/26/02
note: with Luis’ pet peeve #3 below, only 1 indent is necessary
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 11
Wrapping Lines



Break before an operator.
Prefer higher-level breaks to lower-level breaks.
Align the new line with the beginning of the expression
at the same level on the previous line.
// this is preferred because we broke at a higher level
longName1 = longName2 * ( longName3 + longName4 - longName5 )
+ 4 * longname6;
// PREFERRED
longName1 = longName2 * ( longName3 + longName4
- longName5 ) + 4 * longname6; // AVOID
*example taken from Sun’s Java Coding Convention
CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 12
Wrapping Long Method Signatures



break after comma
align parameters after (
except if it’s too long, in which case indent
// CONVENTIONAL INDENTATION (ALIGN TO SAME LOGICAL LEVEL)
someMethod( int anArg, Object anotherArg, String yetAnotherArg,
Object andStillAnother )
{
...
}
// FOR LONG LINES, JUST INDENT ONCE TO AVOID VERY DEEP INDENTS
private static synchronized horkingLongMethodName( int anArg,
Object anotherArg, String yetAnotherArg,
Object andStillAnother )
{
*example taken from Sun’s Java Coding Convention
...
}
CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 13
Luis’s Formatting Pet Peeve #1

NEVER use TAB to indent.
ALWAYS use SPACES.
tabs may be different on different IDEs
 mixing tabs and spaces gets thing misaligned
 (especially when someone else edits your
code and uses the wrong tab size)
Use a consistent number of spaces (2, 3, or 4)
if your IDE supports it, use “Insert Spaces”
option to tell it to automatically convert TABs
to real spaces



CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 14
Luis’s Formatting Pet Peeve #2


ALWAYS enclose the body of an if or
else clause (as well as for, while, do, etc.
statements) in { } even if there is only
one line!
This helps prevent the two problems
we’ve seen



forgetting to add the braces when code is
extended
dangling-else
(Actually, Sun follows this rule too)
CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 15
Example 1 Revisited
(Forgetting Braces)
public class CheckIfLarge
{
public static void main( String args[] )
{
int num;
num = Input.readInt();
if (num > 100)
System.out.println(“Number is large”);
System.out.println(“Thanks”); //executed unconditionally
}
}
CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 16
Example 1 Revisited
(Forgetting Braces)
public class CheckIfLarge
{
This is WRONG!
public static void main( String args[] )
This line is
outside the if.
{
int num;
num = Input.readInt();
if (num > 100)
System.out.println(“Number is large”);
System.out.println(“(It is greater than 100.)”);
System.out.println(“Thanks”); //executed unconditionally
}
}
CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 17
Luis’s Pet Peeve #2
Enclose the
line in a block
even if it’s
just one line!
public class CheckIfLarge
public class CheckIfLarge
{
{
public static void main( String args[] )
public static void main( String args[] )
{
{
int num;
int num;
num = Input.readInt();
num = Input.readInt();
if (num > 100)
if (num > 100)
{
System.out.println(“Number is large”);
System.out.println(“Number is large”);
System.out.println(“Thanks”); //executed unconditionally
}
}
System.out.println(“Thanks”); //executed unconditionally
}
}
}
CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 18
Luis’s Pet Peeve #2
Now you can’t
make a mistake
when adding new
code
public
public class
class CheckIfLarge
CheckIfLarge
{
{
public static void main( String args[] )
public static void main( String args[] )
{
{
int num;
int =num;
num
Input.readInt();
num(num
= Input.readInt();
if
> 100)
{if (num > 100)
{ System.out.println(“Number is large”);
System.out.println(“(It
is greater
than 100.)”);
System.out.println(“Number
is large”);
}}
System.out.println(“Thanks”);
System.out.println(“Thanks”); //executed
//executed unconditionally
unconditionally
}}
}
}
CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 19
Dangling Else & Pet Peeve #2


Pet Peeve #1 says we must use { } after
an if
Where should we put the { } in the
following code? (What’s our intent?)
if (num > 10)
{ if (num > 100)
System.out.println(“Large”);
else
System.out.println(“Small”);
}
CS 21a
7/26/02
Now, we see that
we mis-indented
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 20
Dangling Else & Pet Peeve #2

The complete code
Tedious, but
worth it!
if (num > 10)
{ if (num > 100)
{ System.out.println(“Large”);
}
else
{ System.out.println(“Small”);
}
}
Notice how we
use } with else
CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 21
Luis’s Formatting Pet Peeve #3
Put the { on the line BELOW the if
Style 1 (Sun)
Style 2 (Luis)

if (num > 10) {
if (num > 100) {
System.out.println(“Large”);
} else {
System.out.println(“Small”);
}
}

if (num > 10)
{
if (num > 100)
{
System.out.println(“Large”);
}
else
{
System.out.println(“Small”);
}
}
Sun actually uses Style 1, but Style 2 is better



CS 21a
7/26/02
you can find the matching { just by going straight up
easier to see when you’re forgetting braces
block doesn’t get obscured by long conditions
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 22
Luis’s Formatting Pet Peeve #3

Style 2 solves a problem in Sun’s convention
Style 1
Style 2
//DON'T USE THIS INDENTATION
if ((condition1 && condition2)
|| (condition3 && condition4)
|| !(condition5 && condition6)) {
doSomethingAboutIt();
}
// NO NEED TO INDENT TWICE
if ((condition1 && condition2)
|| (condition3 && condition4)
|| !(condition5 && condition6) )
{
doSomethingAboutIt();
}
//USE THIS INDENTATION INSTEAD
if ((condition1 && condition2)
|| (condition3 && condition4)
|| !(condition5 && condition6)) {
doSomethingAboutIt();
}
CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 23
Luis’s Formatting Pet Peeve #3

To save on vertical space, you may put the {
together with the first line




now same amount of vertical space as Style 1
but, you can still match braces
also still easier to see when you’re forgetting braces
Use sparingly, though. e.g., in slides
Style 1
Style 2
if (num > 10) {
if (num > 100) {
System.out.println(“Large”);
} else {
System.out.println(“Small”);
}
}
CS 21a
7/26/02
if (num > 10)
{ if (num > 100)
{ System.out.println(“Large”);
}
else
{ System.out.println(“Small”);
}
}
© Luis F. G. Sarmenta and John Paul Vergara,
Code Format
Ateneo de Manila University
Slide 24
Luis’s Formatting Pet Peeve #3

How to write if’s



Write if
Type { and }
Insert code in between { and }
if (num > 10)
CS 21a
7/26/02
if (num > 10)
{
}
if (num > 10)
{
if (num > 100)
{
}
else
{
}
}
if (num > 10)
{
if (num > 100)
{
System.out.println(“Large”);
}
else
{
System.out.println(“Small”);
}
}
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 25
Luis’s Pet Peeve #4
if (score >= 90)
{
System.out.println(“A”);
}
else if (score >= 80)
{
System.out.println(“B”);
}
else if (score >= 70)
{
System.out.println(“C”);
}
else if (score >= 60)
{
System.out.println(“D”);
}
else
{
System.out.println(“F”);
}
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
if (num > 10)
{
if (num > 100)
{
System.out.println(“Large”);
}
else
{
System.out.println(“Small”);
}
}
put else, else if,
catch, etc. in next line


CS 21a
7/26/02
helps cases stand out
Code Format
Slide 26
Luis’s Pet Peeve #4b

Write switch statements as follows

different from Sun’s rule because of {
switch (condition)
{
case ABC:
statements;
/* falls through */
case DEF:
statements;
break;
switch (condition)
{
case ABC: statements;
/* falls through */
case DEF: statements;
break;
OR
case XYZ: statements;
break;
case XYZ:
statements;
break;
default: statements;
break;
}
CS 21a
}
7/26/02
default:
statements;
break;
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 27
Luis’s Pet Peeve #5

Use spaces liberally!


makes code much more easier to read and pleasant to look at
Sun rules

space around binary operators (except . )


space between keyword and (




e.g., if ( x == b ) or for ( int i = 0; …
but no space between method name and (
space after comma
space after cast



=, +, !=, ==, etc.
e.g., (int) x or (Product) getObject( “Mango” )
personally, I don’t follow this, so I think this is optional
Additional rules (Luis’s Pet Peeve #5)

use space after the ( and before the )


CS 21a
7/26/02
required after the ( after an if, for, while, etc., or method name
not strictly necessary elsewhere, but it helps
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 28
Luis’s Pet Peeve #5b

Use parens liberally too!




(Sun suggests this too.)
don’t depend on reader to know obscure precedence rules
don’t overuse parens, but feel free to use when it makes things
clearer and easier to read
when using parens around subexpressions, you may omit the
space after ( and before ) if it looks better

but always put a space after the ( following an if, for, etc. or
method
if (a == b && c == d)
// AVOID! TECHNICALLY RIGHT, BUT NOT CLEAR!
if ( ( a == b ) && ( c == d ) ) // RIGHT, but might be too loose
if ( (a == b) && (c == d) )
// OK
if ((a == b) && (c == d))
// OK w/ Sun, but I suggest avoid
CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 29
Pet Peeves Example
void fillRect(int x, int y,
int w, int h, int n) {
offGr.setColor(colorFunc(n));
for(int i=x; i<x+w; i++)
for(int j=y; j<y+h; j++) {
offGr.drawRect(i,j,1,1);
mand[i][j].set(n);
}
}
Which one is
more readable
and pleasant
to the eye?
CS 21a
7/26/02
void fillRect(int x, int y,
int w, int h, int n) {
offGr.setColor(colorFunc(n));
for (int i = x; i < x + w; i++) {
for (int j = y; j < y + h; j++) {
offGr.drawRect(i, j, 1, 1);
mand[i][j].set(n);
}
}
}
void fillRect( int x, int y,
int w, int h, int n )
{
offGr.setColor( colorFunc( n ) );
for ( int i = x; i < (x + w); i++ )
{
for ( int j = y; j < (y + h); j++ )
{
offGr.drawRect( i, j, 1, 1 );
mand[i][j].set( n );
}
}
}
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 30
Summary
General (Sun)

Identifier names





Comments
Indentation


follow capitalization rules!
use succint, descriptive
names
you can use short names, but
only for temporary variables




CS 21a
7/26/02
1.
2.
3.
4.
always indent new blocks
Line Wrapping
Luis’s Pet Peeves
don’t go over 70-75 columns
break after commas
break before operators
align at the same level
5.
Use SPACES, not TABs
ALWAYS use braces
after if, else, for, etc.
Put the { on the line
below
else, else if, and switch
statements
Use spaces and parens
liberally
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 31
Updates and Corrections




Some updates (Feb. 2006)
For real programs (as opposed to code to be shown on
slides), always use 4 spaces for indents
Line wrapping at < 80 columns may not be a strict
requirement anymore as people are starting to have
wider and wider displays
When using automatic formatters (e.g., in Eclipse) it’s
often hard to control how it wraps lines. Thus, I am not
that strict in how this should be done. Generally,
though, if you are not trying to align continuation lines
with certain expressions in the line above, then just
indent the continuation lines once (4 spaces).
CS 21a
7/26/02
© Luis F. G. Sarmenta and John Paul Vergara,
Ateneo de Manila University
Code Format
Slide 32