Formatting Code in Java Common Conventions and Luiss







![Indentation Example public class Check. If. Large { public static void main( String args[] Indentation Example public class Check. If. Large { public static void main( String args[]](https://slidetodoc.com/presentation_image/886883646b6228350a5d1bab0d3d465b/image-8.jpg)
![Indentation Example public class Check. If. Large { public static void main( String args[] Indentation Example public class Check. If. Large { public static void main( String args[]](https://slidetodoc.com/presentation_image/886883646b6228350a5d1bab0d3d465b/image-9.jpg)
![Indentation Example public class Check. If. Large { public static void main( String args[] Indentation Example public class Check. If. Large { public static void main( String args[]](https://slidetodoc.com/presentation_image/886883646b6228350a5d1bab0d3d465b/image-10.jpg)






















- Slides: 32

Formatting Code in Java Common Conventions and “Luis’s Pet Peeves” (Originally given as a lecture in CS 21 a at Ateneo de Manila University. See last slide for updates. ) 12/03/01

Why is Good Format important? n n Your code needs to be readable! Others need to be able to read and understand your code easily n n helps others fix and maintain your code in the future You need to be able to read your code too! n n n avoid syntax errors readability helps debugging future maintenance n CS 21 a 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 12/03/01

Formatting Conventions n n Formatting conventions ensures consistency and therefore, familiarity for readers Sun’s Coding Conventions for Java n n n CS 21 a 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 12/03/01

Identifier names n Class names start upper-cased n n Variable and Method names start lower-cased n n e. g. , Bank. Account, Vehicle. Applet e. g. , alice. Account, honda. Civic 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 n CS 21 a 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 12/03/01

Choosing Names n n In general use descriptive names Try to be succint, but don’t skimp too much, and avoid “skppng vwls” (especially for class names) n n In some cases, OK to use 1 -or-2 letter names n n e. g. , use Bank. Account instead of Bnk. Accnt 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 Bank. Account ba, Garbage. Truck gb, etc. Always use descriptive names for fields and methods CS 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01

Comments n Block-style comments /* * This is a multi-line comment. * Use when you need to write a long comment about a fragment */ n One-line comments n /* C-style comments */ n n use to put descriptive notes before a code fragment // C++ style comment n use at the end of the line n n n usually to describe variables or short pieces of code also use for commenting-out code javadoc comments n n CS 21 a 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 12/03/01

Indentation n Indent when starting out new blocks of code n n n after public class My. Class { after public int my. Method() { after an if ( my. Condition ) { after an else { after a for, while, or do Align the if statement, the {, and the } if ( my. Condition ) { x = x + 1; } n Sun says indent 4 spaces n CS 21 a 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 12/03/01
![Indentation Example public class Check If Large public static void main String args Indentation Example public class Check. If. Large { public static void main( String args[]](https://slidetodoc.com/presentation_image/886883646b6228350a5d1bab0d3d465b/image-8.jpg)
Indentation Example public class Check. If. Large { public static void main( String args[] ) { int num; num = Input. read. Int(); if (num > 100) System. out. println(“Number is large”); System. out. println(“Thanks”); //executed unconditionally } Wrong! } CS 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01
![Indentation Example public class Check If Large public static void main String args Indentation Example public class Check. If. Large { public static void main( String args[]](https://slidetodoc.com/presentation_image/886883646b6228350a5d1bab0d3d465b/image-9.jpg)
Indentation Example public class Check. If. Large { public static void main( String args[] ) { int num; num = Input. read. Int(); if (num > 100) System. out. println(“Number is large”); System. out. println(“Thanks”); //executed unconditionally } Wrong! } CS 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01
![Indentation Example public class Check If Large public static void main String args Indentation Example public class Check. If. Large { public static void main( String args[]](https://slidetodoc.com/presentation_image/886883646b6228350a5d1bab0d3d465b/image-10.jpg)
Indentation Example public class Check. If. Large { public static void main( String args[] ) { int num; num = Input. read. Int(); if (num > 100) System. out. println(“Number is large”); System. out. println(“Thanks”); //executed unconditionally } OK } CS 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01

Wrapping Lines n n n 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. n CS 21 a 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 12/03/01

Wrapping Lines n n n 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 long. Name 1 = long. Name 2 * ( long. Name 3 + long. Name 4 - long. Name 5 ) + 4 * longname 6; // PREFERRED long. Name 1 = long. Name 2 * ( long. Name 3 + long. Name 4 - long. Name 5 ) + 4 * longname 6; // AVOID *example taken from Sun’s Java Coding Convention CS 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01

Wrapping Long Method Signatures n n n break after comma align parameters after ( except if it’s too long, in which case indent // CONVENTIONAL INDENTATION (ALIGN TO SAME LOGICAL LEVEL) some. Method( int an. Arg, Object another. Arg, String yet. Another. Arg, Object and. Still. Another ) {. . . } // FOR LONG LINES, JUST INDENT ONCE TO AVOID VERY DEEP INDENTS private static synchronized horking. Long. Method. Name( int an. Arg, Object another. Arg, String yet. Another. Arg, Object and. Still. Another ) { *example taken from Sun’s Java Coding Convention. . . } CS 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01

Luis’s Formatting Pet Peeve #1 n NEVER use TAB to indent. ALWAYS use SPACES. tabs may be different on different IDEs n mixing tabs and spaces gets thing misaligned n (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 n n n CS 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01

Luis’s Formatting Pet Peeve #2 n n 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 n forgetting to add the braces when code is extended dangling-else (Actually, Sun follows this rule too) CS 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01

Example 1 Revisited (Forgetting Braces) public class Check. If. Large { public static void main( String args[] ) { int num; num = Input. read. Int(); if (num > 100) System. out. println(“Number is large”); System. out. println(“Thanks”); //executed unconditionally } } CS 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01

Example 1 Revisited (Forgetting Braces) public class Check. If. Large { This is WRONG! public static void main( String args[] ) This line is outside the if. { int num; num = Input. read. Int(); if (num > 100) System. out. println(“Number is large”); System. out. println(“(It is greater than 100. )”); System. out. println(“Thanks”); //executed unconditionally } } CS 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01

Luis’s Pet Peeve #2 Enclose the line in a block even if it’s just one line! public class Check. If. Large { { public static void main( String args[] ) { { int num; num = Input. read. Int(); if (num > 100) { System. out. println(“Number is large”); System. out. println(“Thanks”); //executed unconditionally } } } CS 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01

Luis’s Pet Peeve #2 Now you can’t make a mistake when adding new code public class Check. If. Large { { public static void main( String args[] ) { { int num; int =num; num Input. read. Int(); num(num = Input. read. Int(); 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”); //executed unconditionally }} } } CS 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01

Dangling Else & Pet Peeve #2 n n 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 21 a 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 12/03/01

Dangling Else & Pet Peeve #2 n 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 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01

Luis’s Formatting Pet Peeve #3 Put the { on the line BELOW the if Style 1 (Sun) Style 2 (Luis) n 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 n n n CS 21 a 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 12/03/01

Luis’s Formatting Pet Peeve #3 n Style 2 solves a problem in Sun’s convention Style 1 Style 2 //DON'T USE THIS INDENTATION if ((condition 1 && condition 2) || (condition 3 && condition 4) || !(condition 5 && condition 6)) { do. Something. About. It(); } // NO NEED TO INDENT TWICE if ((condition 1 && condition 2) || (condition 3 && condition 4) || !(condition 5 && condition 6) ) { do. Something. About. It(); } //USE THIS INDENTATION INSTEAD if ((condition 1 && condition 2) || (condition 3 && condition 4) || !(condition 5 && condition 6)) { do. Something. About. It(); } CS 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01

Luis’s Formatting Pet Peeve #3 n To save on vertical space, you may put the { together with the first line n n 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 21 a 7/26/02 if (num > 10) { if (num > 100) { System. out. println(“Large”); } else { System. out. println(“Small”); } } Code Format © Luis F. G. Sarmenta and John Paul Vergara, Slide 12/03/01 Ateneo de Manila University

Luis’s Formatting Pet Peeve #3 n How to write if’s n n n Write if Type { and } Insert code in between { and } if (num > 10) CS 21 a 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 12/03/01

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 n n CS 21 a 7/26/02 helps cases stand out Code Format Slide 12/03/01

Luis’s Pet Peeve #4 b n Write switch statements as follows n different from Sun’s rule because of { switch (condition) { case ABC: statements; /* falls through */ case DEF: statements; break; OR case XYZ: statements; break; default: statements; break; } CS 21 a } 7/26/02 default: statements; break; © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01

Luis’s Pet Peeve #5 n Use spaces liberally! n n makes code much more easier to read and pleasant to look at Sun rules n space around binary operators (except. ) n n space between keyword and ( n n e. g. , if ( x == b ) or for ( int i = 0; … but no space between method name and ( space after comma space after cast n n n =, +, !=, ==, etc. e. g. , (int) x or (Product) get. Object( “Mango” ) personally, I don’t follow this, so I think this is optional Additional rules (Luis’s Pet Peeve #5) n use space after the ( and before the ) n n CS 21 a 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 12/03/01

Luis’s Pet Peeve #5 b n Use parens liberally too! n n (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 n 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 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01

Pet Peeves Example void fill. Rect(int x, int y, int w, int h, int n) { off. Gr. set. Color(color. Func(n )); for(int i=x; i<x+w; i++) for(int j=y; j<y+h; j++) { off. Gr. draw. Rect(i, j, 1, 1); mand[i][j]. set(n); } } Which one is more readable and pleasant to the eye? CS 21 a 7/26/02 void fill. Rect(int x, int y, int w, int h, int n) { off. Gr. set. Color(color. Func(n )); for (int i = x; i < x + w; i++) { for (int j = y; j < y + h; j++) { off. Gr. draw. Rect(i, j, 1, 1); mand[i][j]. set(n); } } } void fill. Rect( int x, int y, int w, int h, int n ) { off. Gr. set. Color( color. Func( n ) ); for ( int i = x; i < (x + w); i++ ) { for ( int j = y; j < (y + h); j++ ) { off. Gr. draw. Rect( i, j, 1, 1 ); mand[i][j]. set( n ); } } } © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01

Summary General (Sun) n Identifier names n n n Comments Indentation n n follow capitalization rules! use succint, descriptive names you can use short names, but only for temporary variables n n CS 21 a 7/26/02 1. 2. 3. 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 4. 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 12/03/01

Updates and Corrections n n 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 21 a 7/26/02 © Luis F. G. Sarmenta and John Paul Vergara, Ateneo de Manila University Code Format Slide 12/03/01