Indentatin Prperly indented cde is much easier t read than slppily indented cde. Yur TA will appreciate indented cde when grading, and yu ll appreciate nt lsing pints fr indentatin (: Indent yur cde using the fllwing rule. Mst structures in Java start and end with curly braces { (classes, methds, lps, cnditinal statements, etc). Everything within a set f curly braces shuld be indented ne level further than the curly braces were. Fr example a class has n indentatin, a methd in a class has 1 level f indentatin, a lp in a methd in a class has 2 levels f indentatin and s n. A level f indentatin is usually 3 r 4 spaces (It desn t matter which yu pick, just be cnsistent. jgrasp default is 3). With 3 space indentatin cde shuld lk like this: public class BeautifulIndentatinExample { public static vid beautifullyindentedmethd() { fr (int i = 0; i < 5; i++) { if (i % 2 == 0) { System.ut.println( Inside 4 braces, Indented 12 spaces ); public static vid anthermethd() { System.ut.println( Inside 2 braces, Indented 6 spaces ); It is pssible t mit curly braces in sme cases. Yu must still indent as if they were there. The fllwing culd be substituted fr the blue lines abve: fr (int i = 0; i < 5; i++) if (i % 2 == 0) System.ut.println( 2 mitted braces, Still 12 spaces ); Spacing Prper spacing helps with readability as well. Mst java prgrammers fllw the fllwing cnventins. It s easiest t shw them thrugh examples Gd spacing Bad spacing int i = methdcall() * j + j % 4; fr (int i = 0; i < 10; i++) { while (sum < target) { public vid mymethd(int x, int y) { methdcall(param1, param2); public class F { int[] myarray = new int[x + 1]; int i=methdcall()*j+j%4; fr(int i=0;i<10;i++){ while(sum<target){ public vid mymethd (int x,int y){ methdcall (param1,param2); public class F{ int[] myarray=new int[x+1];
Cmmenting Cmments can make cde easier t understand, especially fr smene wh did nt write the cde. Place a cmment at the start f each file with yur name, the date, the class (ie CSE 142 AE), yur TA s name, and the assignment number/title. Als include a descriptin f what the prgram des. Cmment each methd with a high level descriptin f what the methd des. In particular describe legal values fr each parameter, if there are any special values that culd be returned, and any cnditins that culd cause an exceptin t be thrwn. Gd cmments describe what a prgram r methd des (behavir), but nt hw the methd r prgram accmplishes that gal (implementatin). A client f yur cde desn t care and shuldn t need t knw hw yur cde wrks (ie des it use a fr lp r a while lp). In additin, adding implementatin details makes it difficult t change yur cde later. If yu mit implementatin details, hwever, yu can switch the implementatin withut having t change the guarantees that yur cmments make t the client. There are tw ways t write cmments in Java. Single line cmments start with // like this: // This is a cmment. Multi line cmments start with a /* and end at the first */ like this: /* This is a cmment that spans multiple lines */ Bad cmment: // This is the methd that prints the values in the ArrayList // using a fr lp. Shuld thrw exceptin if the list is null public static vid print(arraylist list) {... Why this cmment is bad: Language. We already knw that it's a methd, s just say what it des instead f this methd des. Als, dn t say the methd shuld d smething if yu prgrammed it crrectly, it will d it. Implementatin details. Maybe later yu learn hw t use an iteratr and decide t change hw the methd wrks. But since yu've dcumented that the cde uses a fr lp, yu can't g back and change it. It is therefre better t tell what the methd des rather than hw it des it. Output r return value. The user prbably wants t knw hw the results lk - des it print each value n separate lines r print it in reverse rder? That makes a big difference. Exceptins. The user als wants t knw hw t avid breaking the methd, s it's gd t tell them precisely what will cause an exceptin. In case they d break the methd, they als want t knw what type f exceptin it is in rder t handle the errr in their prgram Gd cmment: // Prints the cntents f list as cmma-separated values. // Thrws an IllegalArgumentExceptin if list is null. public static vid print(arraylist list) {...
Chapter 1 Naming cnventins: Classes Start with a capitl letter, each subsequent wrd starts with a capitl letter. MyAwesmeClass Methds Start with a lwercase letter, each subsequent wrd starts with a capitl letter. myawesmemethd Methds Use static methds t break prgrams int reusable pieces. Reduce redundancy! Avid trivial methds, r methds that d t little. main shuld be a cncise, high-level summary f yur prgram. N details in main. Leave a blank line between methd definitins. Printing Fr a blank line, use System.ut.println(); nt System.ut.println( ); Cmbine print statements. System.ut.print( ** ); instead f 2 calls t System.ut.print( * ); System.ut.println( * ); instead f System.ut.print( * ); System.ut.println(); Chse the apprpriate print methd System.ut.println( hell ); nt System.ut.print( hell\n ); General Cnventins Java desn t care abut spacing, but we d. Place each statement n its wn line. Each line shuld be less than 100 characters. Chapter 2 Variables Chse the crrect type fr variables: Use int when yu nly need whle numbers. Use duble when yu need decimal precisin. Declare variables in the smallest scpe pssible. If yu nly need a variable inside f a lp, then declare it in the lp. Chse variable names that succinctly describe what the variable represents. average is a better variable name than a. It lets anyne reading yur cde knw what the variable represents withut having t read the cde that cmputes an average. Dn t rely n cntext t give meaning t yur variable names. The cntext f yur variable may change as yu edit yur cde. Variables fllw the same naming cnventins as methds. camelcaseyurvariablenames Cnstants Use a class cnstant when yu want t define a single value that wn t change during the executin f yur prgram. The naming cnventin fr cnstants is CAPITOLS_WITH_UNDERSCORES Cnstants are declared with the keywrds public static final fr Lps
Use fr lps t repeat cde a specific number f times. Reduce redundancy! Yu dn t need a lp that runs nly 1 time. Chapter 3 Chapter 4 Parameters Use parameters when yu can t make methds mre general. Dn t include unnecessary parameters in a methd declaratin; every parameter shuld be used. Dn t pass class cnstants as parameters, they re accessible everywhere within the class. Returns Use return statements t mve data frm a methd t its caller. Declare a methd as vid if yu dn t need t return anything. Objects Create a single Graphics bject r Scanner bject and pass it t yur methds. If/else statements Use the apprpriate cnditinal structure if/if any f the statement bdies culd execute, r all, r nne if/else if 0 r 1 f the statement bdies will execute if/else exactly 1 f the statement bdies will execute Factring Cmmn cde at the beginning f each branch f a cnditinal statement shuld be pulled ut befre the cnditin Cmmn cde at the end f each branch f a cnditinal statement shuld be pulled ut after the cnditin Exceptins Cnstruct Exceptins with a useful errr message Chapter 5 while Lps Use while lps t repeat cde an unspecified number f times. A d/while lp runs the lp bdy befre checking the cnditin Fencepsting Sentinels Yu may need t prime a lp t get it t execute the first time Yu als may need t pull the cde fr ne iteratin f the lp utside f the lp This is preferable t slving yur fencepst prblem by using a cnditinal in the lp Randm Create a single Randm bject and pass it t yur methds. blean zen Bad Gd if (myvar == true) { if (myvar) { if (myvar == false) { if (!myvar) { if (myvar == true) return myvar; return true;
Chapter 6 else return false; Using a Scanner n a File Be careful mixing next(), nextint(), and nextduble() with nextline(). It s easy t create bugs. Yu may nt want t initialize variables in the smallest pssible scpe in ne case. If initializing yur variable culd ptentially thrw an exceptin (such as initializing a Scanner n a File), yu may want t d it in main and pass the variable int each methd instead f adding a thrws clause t each methd. Chapter 7 Arrays Use arrays t stre a sequence f data that all has the same type The easiest way t lp ver an array when yu need the index f each element: fr (int i = 0; i < myarray.length; i++) { The easiest way t lp ver an array when yu dn t need the index f each element: fr (int element : myarray) { Smetimes it s apprpriate t return an array, but dn t use it as a hack fr returning tw unrelated pieces f data Als dn t pass an array f unrelated data t avid declaring extra parameters Rather than using many lines f cde t initialize an array, shrthand it like this: int[] myarray = {1, 2, 3, 4, 5; Chapter 8 Objects Create private fields with getters/setters rather than leaving fields public. This allws yu t make sure yur bject is always in a valid state. Als yu can change the implementatin later withut breaking client cde. Helper methds shuld be private as well. Use cnstructr verlading t reduce redundancy within yur bjects. Reduce redundancy! Chapter 9 Inheritance Use inheritance t share cmmn functinality acrss classes. Reduce redundancy! This als lets clients re-use cde t interact with different types f bjects. Use prtected fields t let a subclass interact with yur fields. Cmpsitin Inheritance is nt always apprpriate, smetimes yu need t use cmpsitin. This is the difference between an is-a relatinship and a has-a relatinship.