0% found this document useful (0 votes)
51 views

Java Coding Style Short Cuts and Basics

The document outlines Java coding style conventions for formatting, comments, variable declarations, control structures, alignment and indentation, multiple statements per line, operator spacing, shorthand operators, and naming conventions. Key recommendations include using descriptive identifier names, consistent indentation, commenting non-obvious code, and placing braces and parentheses consistently.

Uploaded by

Jimmy Dukes
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Java Coding Style Short Cuts and Basics

The document outlines Java coding style conventions for formatting, comments, variable declarations, control structures, alignment and indentation, multiple statements per line, operator spacing, shorthand operators, and naming conventions. Key recommendations include using descriptive identifier names, consistent indentation, commenting non-obvious code, and placing braces and parentheses consistently.

Uploaded by

Jimmy Dukes
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 14

'

Java Coding Style Conventions


This appendix describes Java coding-style conventions. Most of these guidelines are widely accepted. However, alternative guidelines do exist in certain areas. The coding conventions presented in this docu ent are for the ost part a si plified subset of the coding conventions presented on Sun!s Java Code Conventions "eb page# http://java.sun.com/docs/codeconv/ $f you have a style %uestion that is not addressed in this docu ent, refer to Sun!s "eb page. "hile reading the following sections, refer to the exa ple progra the style in that exa ple. Prologue '. (ut this prologue section at the top of the file# /*********************************************** * <filename> * <programmer's name> * * <file description> ***********************************************/ ). $nclude a blan* line below the prologue section. Section Delimiting '. +fter state variable definitions and between constructor and li*e this# ethod definitions, enter a line of stars, in the last section. &ou can i ic

//*********************************************************** ,eave a blan* line above and below this line of stars. ). "ithin a large constructor or ethod, insert blan* lines between logical sections of code. -or exa ple, unless the loops are s all and inti ately related, enter a blan* line between the end of one loop and the beginning of another loop. Embedded Comments '. (rovide co ents for code that ight be confusing to so eone reading your progra ti e. +ssu e the reader understands Java syntax. ). .o not co ent code that is obvious. -or exa ple, this co exhibits poor style# for the first

ent is unnecessary and therefore

for (int i= ! i<" ! i##$

// for loop header

This co ent 6ust adds clutter. ents.

/. "rite your progra s with clear, self-docu enting code in order to reduce the need for co -or exa ple, use ne onic 0descriptive1 identifier na es. 2. +lways include a single space between the // and the co 3. The co
o

ent text.

ent!s length deter ines its for at. $f the co ent will occupy ore than one line, use co plete lines, li*e this#

// %his is a &loc' comment. (se it for comments that // occup) more than one line. *ote the alignment for /'s // and words.
o

$f a co ent is to reside on a line by itself, position it above the line of code it describes. $ndent the // the sa e as the described line of code. $nclude a blan* line above the co ent line. Here!s an exa ple# // +ispla) error if invalid file name. if (file*ame == null ,, filename.get*ame($.e-uals(..$$ / 01ption2ane.show3essage+ialog(this4 file5rror3sg$! 6

Many co ents are s all enough to fit in space to the right of the code they describe. "henever possible, all such co ents should start in the sa e colu n, as far to the right as possible. The following exa ple de onstrates proper positioning for short co ents. float testScores = new float78 9! // inde: is student num&er int student! ... while (testScores7student9 >= $ / testScores7student9 = score! ... // negative inde: -uits

4. (rovide an end co ent for each closing brace that is a significant nu ber of lines 0five or down fro its atching opening brace. -or exa ple, note the // end for row and // end getSum co ents below#

ore51

/ pu&lic float getSum(float ta&le79794 int rows4 int cols$ / for (int row= ! row<rows! row##$ / for (int col= ! col<cols! col##$ / sum #= ta&le7row97col9! 6 6 // end for row return sum! 6 // end getSum

Variable Declarations '. 7or ally, you should declare only one variable per line. -or exa ple# float avgScore! int num1fStudents! // average score on the test // num&er of students in the class

8xception# $f several variables are inti ately related, it is acceptable to declare the exa ple# int :4 )4 ;! // coordinates for a point

together on one line. -or

). 7or ally, you should include a co

ent for each variable declaration line.

8xception# .on!t include a co ent for na es that are obvious 0ie., student<d, 2<1 or standard 0ie., i for a for loop index variable, ch for a character variable1. Braces that Surround One Statement '. -or if, else, for, while, and do constructs that execute only one state ent, it!s good practice to treat that one state ent as though it were a co pound state ent and enclose it in braces, li*e this# for (int i= ! i<scores.length! i##$ / sum1fS-uares #= scores7i9 * scores7i9! 6 ). 8xception# $f it would be illogical to add another state ent to the construct at a later ti e, you ay o it the curly braces when the o ission i proves readability. -or exa ple, this is acceptable for an experienced progra er#

2 for (! num>==! num>>$ factorial *= num!

Placement of Braces '. (lace opening and closing braces on lines by the selves such that the braces are aligned with the line above the opening brace. -or do loops, put the while condition on the sa e line as the closing brace. ). 8xa ples# pu&lic class ?ounter / <field-and-method-declarations> 6 if (...$ / <statements> 6 else if (...$ / <statements> 6 else / <statements> 6 for/while (...$ / <statements> 6 do / <statements> 6 while (...$!

3 switch (...$ / case ... : <statements> &rea'! case ... : <statements> &rea'! ... default: <statements> 6 int do<t($ / <statements> 6 /. 9race align ent is a contentious issue. Sun!s Java Code Conventions "eb site reco ends putting the opening curly brace at the end of the previous line. This is one place where this docu ent!s conventions diverge fro Sun!s conventions. "e reco end that you put the opening curly brace on its own line because that helps a*e co pound state ents stand out. 2. -or e pty-bodied constructors, place the opening and closing braces on the sa e line and separate the with a space, li*e this# pu&lic ?ounter($ / 6

The else if Construct '. $f the body of an else is 6ust another if, for an else if construct 0put the else and the if on the sa e line1. See the above brace place ent section for an exa ple of a proper else if construct. Alignment and Indentation '. +lign all code that is logically at the sa e level. See the above brace place ent section for exa ples of proper align ent. ). $ndent all code that is logically inside other code. That is, for nested logic, use nested indentation. -or exa ple#

4 for (...$ / while (...$ / <statements> 6 6 /. &ou ay use an indentation width of two to five spaces. :nce you choose an indentation width, you should stic* with it. ;se the sa e indentation width throughout your progra . 2. "hen a state ent that is too long to fit on one line, write it on ultiple lines such that the continuation lines are indented appropriately. $f the long state ent is followed by a single state ent that is logically inside of the long state ent, use braces to enclose the single state ent. ;se either of the following techni%ues to indent continuation lines#
o

$ndent to a colu n position such that si ilar entities are aligned. $n the exa ple below, the entities that are aligned are the three ethod calls# while (&uc'ling%est(e:pected@oad4 testAidth4 length$ BB stress%est(e:pected@oad4 testAidth$ BB deflection%est(recommendedAidth4 length$$ / num1fSafeCeams##! 6

$ndent the sa e nu ber of spaces as all other indents. -or exa ple# while (&uc'ling%est(e:pected@oad4 testAidth4 length$ BB stress%est(e:pected@oad4 testAidth$ BB deflection%est(recommendedAidth4 length$$ / num1fSafeCeams##! 6

Multiple Statements on One ine '. 7or ally, each state ent should be put on a separate line. 8xception# $f state ents are inti ately related and very short, it is acceptable 0but not re%uired1 to put the together on one line. -or exa ple# a##! &##! c##! ). -or assign ent state ents that are inti ately related and use the sa e assigned value, it is acceptable 0but not re%uired1 to co bine the into one assign ent state ent. -or exa ple#

= : = ) = ; = !

Spaces !ithin a ine of Code '. 7ever put a space at the left of a se icolon. ). (arentheses#

7ever enter a space on the inside of enclosing parentheses. $f the entity to the left of a left parenthesis is an operator or a construct *eyword 0 if, switch, etc.1, then precede the parenthesis with a space. $f the entity to the left of a left parenthesis is a with a space. ethod na e, then do not precede the parenthesis

-or exa ple# if ((a == " $ BB (& == " $$ / print<t(:$! 6 /. :perators#

7or ally, an operator should be surrounded by spaces. -or exa ple# if (response == .avg.$ / ) = (a # &$ / =! 6

Special cases# o Co plex expressions# "ithin an inner co ponent of a co plex expression, do not surround the inner co ponent!s operators with spaces. Two co on occurrences of co plex expressions are conditional expressions and for loop headers. See the exa ples below. .ot operator < no spaces at its left or right. Co a operator - no space at its left. ;nary operators < no space between unary operator and its associated operand.

o o o

-or exa ple#

> if (;ero3inimum$ / : = (:< D : :$! 6 while (list".row E= list=.row$ / <statements> 6 for (int i= 4j= ! i<=&ig<! i##4j##$ / <statements> 6

Shortcut Operators '. ;se incre ent and decre ent operators instead of their e%uivalent longer for s. -or exa ple# .o not use : = : # " : = : F " ;se this :## or ##: 0depending on the context1 :>> or >>: 0depending on the context1

). ;se co pound assign ents instead of their e%uivalent longer for s. -or exa ple# .o not use ;se this

: = : # G : #= G : = : * (H # )$ : *= H # ) "aming Con#entions '. ;se eaningful na es for your identifiers. ultiple words, use underscores to

). -or na ed constants, use all uppercase letters. $f there are separate the words. -or exa ple#

pu&lic static final int S5?1*+SI<*I+JK = 8LM private final int JNNJKIS<O5!

/. -or class na es 0and their associated constructors1, use uppercase for the first letter and lowercase for all other letters. $f there are ultiple words in the class na e, use uppercase for the first letter of all words. -or exa ple#

B pu&lic class <nner?ircle / pu&lic <nner?ircle(radius$ / <constructor-body> 6 2. -or all identifiers other than constants and constructors, use all lowercase letters. $f there are ultiple words in the identifier, use uppercase for the first letter of all words that follow the first word. -or exa ple# float avgScore! int num1fStudents! // average score on the test // num&er of students in the class

Methods and Constructor Organi$ation '. 7or ally, each contains# ethod definition should be preceded by a prologue section. The ethod prologue

a blan* line a line of A!s a blan* line a description of the purpose of the ethod a blan* line para eter descriptions 0for non-obvious para eters1 a blan* line $deally, all ethod para eters should use descriptive enough na es so that the purpose of each para eter is inherently obvious. However, if this is not the case, then include a list of para eters and their descriptions in a ethod prologue above the ethod heading. -or exa ple, in a tic-tac-toe progra , a ethod that handles a player!s ove would be relatively co plicated and would re%uire a ethod prologue li*e this# //***************************************************** // // // // // // %his method prompts the user to enter a move4 validates the entr)4 and then assigns that move to the &oard. <t also chec's whether that move is a winning move. 2arameters: &oard > the tic>tac>toe &oard/arra) pla)er > holds the current pla)er ('P' or '1'$

pu&lic void handle3ove(char7979 &oard4 char pla)er$ / +ssu ing you describe instance and class variables when you declare the , you should not provide prologues for ?trivial@ accessors, utators, and constructors that 6ust read or write instance and class

'C variables. :n the other hand, if a utator perfor s validation on a para eter prior to assigning it to its associated instance variable, then it is not trivial, and you should include a prologue with it. The sa e reasoning applies to a constructor. + si ple-assign ent constructor should not have a prologue. + validation constructor should have a prologue. ). $n the interest of grouping si ilar things together, you should o it asteris* lines between trivial constructors, and you should o it asteris* lines between utators and accessors. +ssu e that a class contains two trivial constructors, several utator and accessor other si ple ethods. Here!s the fra ewor* for such a class# <class-heading> / <instance-variable-declarations> //********************************************************* <trivial-constructor-definition> <trivial-constructor-definition> //********************************************************* <mutator-definition> <mutator-definition> <accessor-definition> <accessor-definition> //********************************************************* <simple-method-definition> //********************************************************* <simple-method-definition> 6 $n the above fra ewor*, note that there are no descriptions for trivial constructors, accessors, or utators, or for si ple ethods. 7ote also that there is a line of asteris*s above the first utator, but not above the subse%uent utator and accessors. Those o issions help to a*e a progra ore readable by grouping si ilar things together. +lso note that there are no co ents above each of the two si ple ethods at the botto of the class, but there are lines of asteris*s. /. (lace local variable declarations i ediately below the declarations within the executable code. ethod heading. .o not place local variable ethods, and two

8xception# .eclare a for loop index variable within its for loop header.

''

Class Organi$ation '. 8ach of your classes ay contain the following ite s 0in the following order1#

class prologue section import state ents constant class variables non-constant class variables instance variables abstract ethods constructors instance ethods class ethods ). 7or ally you should place a main ethod and any of its helper ethods in its own separate driver class. 9ut it!s so eti es appropriate to include a short main ethod within the class it drives as an e bedded testing tool. (ut such a ethod at the end of the class definition. Sample %a#a Program

')

/***************************************************************** * Student.java * +ean B +ean * * %his class handles processing of a student's name. *****************************************************************/ import java.util.Scanner! pu&lic class Student / private String first = ..! // student's first name private String last = ..! // student's last name //************************************************************** pu&lic Student($ / 6 // %his constructor verifies that each passed>in name starts // with an uppercase letter and follows with lowercase letters. pu&lic Student(String first4 String last$ / setQirst(first$! set@ast(last$! 6 //************************************************************** // %his method verifies that first starts with an uppercase // letter and contains lowercase letters thereafter. pu&lic void setQirst(String first$ / // 7J>O97a>;9* is a regular e:pression. See J2< 2attern class. if (first.matches(.7J>O97a>;9*.$$ / this.first = first! 6 else / S)stem.out.println(first # . is an invalid name.Rn. # .*ames must start with an uppercase letter and have. # . lowercase letters thereafter..$! 6 6 // end setQirst -igure +3.'a Student class, used to illustrate coding conventions < part +

'/ //************************************************************** // %his method verifies that last starts with an uppercase // letter and contains lowercase letters thereafter. pu&lic void set@ast(String last$ / // 7J>O97a>;9* is a regular e:pression. See J2< 2attern class. if (last.matches(.7J>O97a>;9*.$$ / this.last = last! 6 else / S)stem.out.println(last # . is an invalid name.Rn. # .*ames must start with an uppercase letter and have. # . lowercase letters thereafter..$! 6 6 // end set@ast //************************************************************** // 2rint the student's first and last names. pu&lic void printQull*ame($ / S)stem.out.println(first # . . # last$! 6 // end printQull*ame 6 // end class Student -igure +3.'b Student class, used to illustrate coding conventions < part 9

'2 /*************************************************** * Student+river.java * +ean B +ean * * %his class acts as a driver for the Student class. ***************************************************/ pu&lic class Student+river / pu&lic static void main(String79 args$ / Student s"! // first student Student s=! // second student s" = new Student($! s".setQirst(.Jdee&.$! s".set@ast(.0arrah.$! s= = new Student(.Seejoo.4 .?hun.$! s=.printQull*ame($! 6 // end main 6 // end class Student+river -igure +3.) Student+river class This is used with the Student class in -igures +3.'a and +3.'b.

You might also like