There’s no one, right way to stylize code. But there are definitely a lot of wrong (or, at least, bad ways). Even so, this course does ask that you adhere to the conventions below so that I can reliably analyze your code’s style. Similarly do companies typically adopt their own, company-wide conventions for style.
By convention the maximum length of a line of code is 80 characters long in Java, with that being historically grounded in standard-sized monitors on older computer terminals, which could display 24 lines vertically and 80 characters horizontally. Though modern technology has obsoleted the need to keep lines capped at 80 characters, it is still a guideline that should be considered a “soft stop,” and a line of 100 characters should really be the longest you write in Java, else readers will generally need to scroll. If you need more than 100 characters, it may be time to rethink either your variable names or your overall design!
Comments make code more readable, not only for others (e.g., your teacher) but also for you, especially when hours, days, weeks, months, or years pass between writing and reading your own code. Commenting too little is bad. Commenting too much is bad. Where’s the sweet spot? Commenting every few lines of code (i.e., interesting blocks) is a decent guideline. Try to write comments that address one or both of these questions:
What does this block do?
Why did I implement this block in this way?
Within methods, use “inline comments” and keep them short (e.g., one line), else it becomes difficult to distinguish comments from code, even with syntax highlighting. Place the comment above the line(s) to which it applies. No need to write in full sentences, but do capitalize the comment’s first word (unless it’s the name of a function, variable, or the like), and do leave one space between the // and your comment’s first character, as in:
// Convert Fahrenheit to Celsius
double c = 5.0 / 9.0 * (f - 32.0);
In other words, don’t do this:
//Convert Fahrenheit to Celsius
double c = 5.0 / 9.0 * (f - 32.0);
Or this:
// convert Fahrenheit to Celsius
double c = 5.0 / 9.0 * (f - 32.0);
Or this:
double c = 5.0 / 9.0 * (f - 32.0); // Convert Fahrenheit to Celsius
Atop your .java files should be a multi-line comment that summarizes what your program does, as in:
/**
* Says hello to the world
*/
Atop each of your methods (except, perhaps, main()), meanwhile, should be a multi-line comment that summarizes what your method is doing, as in:
/**
* Returns the square of n
*/
int square(int n)
{
return n * n;
}
Conditions should be styled as follows:
if (x > 0) {
System.out.println("x is positive");
} else if (x < 0) {
System.out.println("x is negative");
} else {
System.out.println("x is zero");
}
Notice how:
open curly brackets ({) are at the end of the header line for a block of code;
closing curly brackets (}) are at the beginning of the line after the block of code;
each else or else if statement is preceded by } and followed by {;
there’s a single space after each if;
each call to System.out.println is indented with 4 spaces;
there are single spaces around the > and around the <; and
there isn’t any space immediately after each ( or immediately before each ).
Don’t do this:
if (x < 0)
{
printf("x is negative\n");
} else if (x < 0)
{
printf("x is negative\n");
}
And definitely don’t do this:
if (x < 0)
{
printf("x is negative\n");
}
else
{
printf("x is negative\n");
}
Declare a switch as follows:
switch (n) {
case -1:
System.out.println("n is -1");
break;
case 1:
System.out.println("n is 1");
break;
default:
System.out.println("n is neither -1 nor 1");
break;
}
Notice how:
each curly brace is on its own line;
open curly bracket ({) is on the same line as switch;
closing curly bracket (}) is on its own line;
there’s a single space after switch;
there isn’t any space immediately after each ( or immediately before each );
the switch’s cases are indented with 4 spaces;
the cases’ bodies are indented further with 4 spaces; and
each case (including default) ends with a break.
Be sure to declare main with:
public static void main(String[] args) {
}
As for your own methods, be sure to define them similarly, with the open curly bracket ({) on the same line as the method name and the closing curly bracket (}) on its own line, just as we’ve done with main.
Indent your code four spaces at a time to make clear which blocks of code are inside of others. If you use your keyboard’s Tab key to do so, be sure that your text editor is configured to convert tabs (\t) to four spaces, else your code may not print or display properly on someone else’s computer, since \t renders differently in different editors. (If using CS50 IDE, it’s fine to use Tab for indentation, rather than hitting your keyboard’s space bar repeatedly, since we’ve pre-configured it to convert \t to four spaces.)
Here’s some nicely indented code:
// Print the elements of a 2D array
for (int r = 0; r < arr2D.length; r++) {
for (int c = 0, c < arr2D[0].length; c++) {
System.out.println(arr2D[r][c]);
}
System.out.println();
}
Whenever you need temporary variables for iteration, use i, then j, then k, unless more specific names would make your code more readable (see the example under Indentation above):
for (int i = 0; i < LIMIT; i++) {
for (int j = 0; j < LIMIT; j++) {
for (int k = 0; k < LIMIT; k++) {
// Do something
}
}
}
If you need more than three variables for iteration, it might be time to rethink your design!
Declare while loops as follows:
while (condition) {
// Do something
}
Notice how:
open curly bracket ({) is on the same line as while;
closing curly bracket (}) is on its own line;
there’s a single space after while;
there isn’t any space immediately after the ( or immediately before the ); and
the loop’s body (a comment in this case) is indented with 4 spaces.
Declare do ... while loops as follows:
do {
// Do something
}
while (condition);
Notice how:
open curly bracket ({) is on the same line as do;
closing curly bracket (}) is on its own line;
there’s a single space after while;
there isn’t any space immediately after the ( or immediately before the ); and
the loop’s body (a comment in this case) is indented with 4 spaces.
Make sure you scope your variables as tightly as possible. For instance, if i is only needed for the sake of a loop, declare i within the loop itself:
for (int i = 0; i < LIMIT; i++) {
System.out.println(i);
}
Though it’s fine to use variables like i, j, and k for iteration, most of your variables should be more specifically named. If you’re summing some values, for instance, call your variable sum. If your variable’s name warrants more than one word (e.g., isReady), use Camel Case, a convention popular in Java.
If declaring multiple variables of the same type at once, it’s fine to declare them together, as in:
int quarters, dimes, nickels, pennies;
Just don’t initialize some but not others, as in:
int quarters, dimes = 0, nickels = 0 , pennies;
Variable and method names should always begin with a lower-case letter. If the name warrants more than one word, use Camel Case:
String name;
double changeAmount;
public int move() {
}
private boolean isReady() {
}
Class and interface names should always begin with an upper-case letter. If the name warrants more than one word, use Camel Case:
public interface House {
}
public class ChangeMaker {
}
Constants (marked with the keyword final) should be in all upper-case. If the name warrants more than one word, use underscores (_):
final int LEVEL = 10;
final double RATE_OF_CHANGE = 2.34;