Coding Style Guidelines for Java Programming

Objectives
to give guidelines for good Java coding
I use these guidelines when marking projects, exams,
etc.
16.
 Coding Style
DIN61-222 Adv. Prog. (Java)
Semester 1, 2019-2020
1
Overview
1
. Class-related Guidelines
2
. Method-related Guidelines
3
. Comment-related Guidelines
4
. Layout-related Guidelines
5
.
 
 More Information
2
1
.  Class-related Guidelines
1.1.  Class Names
1.2.  Object Names
1.3.  Class Data
1.4.  Static for Constants
1.5.  Initializing Variables
1.6.  Few Global Variables
1.7.  Get and Set
1.8.  Change Date Locally
1.9.  Classes in Files
3
1.1
. Class Names
A class name should be a 
noun
the noun is often a 
"type-of-thing"
 word
e.g. Plane, Car, Database
long names may use several words
e.g. JumboJet, Toyota, StudentDb
starts with
an uppercase
letter
each word
starts with
an uppercase
letter
4
1.2
.  Object Names
An object name should be a 
noun
the noun is often the 
class 
word and a number
e.g. plane
1
 car
2
, database
5
but try to use names with more meaning
e.g. andrewDb, coeCar
starts with
a lowercase
letter
5
1.3
. Class Data
Always define data as 
private
e.g. 
 
private int x;
Avoid the keywords 
public
, 
protected
Always include a visibility keyword
e.g.
   
int x
;
  
// 
bad
: unclear
6
1.4
.  Static for Constants
Only use 
static
 
to declare constants:
 
private 
static
 final int MAXLEN = 
120;
always write 
static final
always write the constant name in 
all 
uppercase
(Almost) n
ever use 
static
 
with methods
(
except
 for 
main()
)
7
1.5
. Initializing Variables
Global objects and variables should be initialised
inside a method (often the constructor):
 
private int counter;  // global
public Matrix()
{ counter 
=
 
0
;  
}
It 
may
 be okay to initialise 
simple
 global variables
(e.g. 
int
s, 
double
s) globally:
 
private int counter 
=
 
0
;  // global
8
1.6
.  Few Global Variables
Keep the number of global variables in a class to a
minimum.
Bad
 
Code:
 
private int x;  // global in class
public void calc()
{ 
 
x 
=
 
0
; bar(
5
);
  System.out.println(x); }
private void bar(int y)
{ x = x + y; }
continued
9
The code is bad because a person who looks at a
class 
will need to check every line of code
 to find out
where x is used.
The use of globals often means that a student is not
sure how to change variables or objects inside Java
methods
continued
10
Good
 Code:
 
public void calcX()
{ int x 
=
 
0
;
  
 
x 
=
 addX(x,
5
);  // x gets new value
  System.out.println(“x= “ + x);
}
private int addX(int x, int y)
{ return x+y; }
continued
the global x 
has gone
x in addX() is a
copy
 of the x in
calcX()
11
The code is better since 
x
 is local to the method
that uses it, and is passed as a parameter to the
other method
Note how 
x
 is updated by using 
return
the following code will 
not
 change 
x
 in 
calcX()
:
  
private void addX(int x, int y)
 
{ x = x+y; }
continued
12
Good
 code with objects:
 
public void calcMatrix()
{ 
 
Matrix m
1
 = new Matrix();
   processMatrix(m1);
   m
1
.print();
}
  
private void processMatrix(Matrix m)
{ // change m (really m
1
) }
objects are
passed using
call
-
by
-
reference,
so do not need
to be returned
13
1.7
. Get and Set
Private data which will be accessible outside an object
should be given 
set
 
and 
get
 
methods
 
public class BankAccount
{
  private double balance;
 
  public double 
getBalance
()
  {  return balance;  }
  public void 
setBalance
(double b)
  { balance = b;  }
  
:
}
continued
14
The method names must be 
set<Variable>
 and
get<Variable>
.
Only include a 
set
 
method if the variable needs to be
changed.
15
1.8
. Change Data Locally
Methods that change data should be in the class where
the data is declared.
Bad
 
code:
 
public static void main(String args[])
{
  BankAccount myacc = new BankAccount();
  double bal = myacc.getBalance();
 
  
bal = bal * 
1.15
;
   // calculate interest
  myacc.setBalance(bal);
}
continued
bal
 
change 
is 
done in main()
16
Good
 code (in 
BankAccount
):
 
public void applyInterest(double interest)
{ bal = bal * interest; }
in 
main()
:
 
BankAccount myacc = new BankAccount();
myacc.applyInterest(
1.15
);
bal
 
change done in 
the 
BankAccount 
object
17
1.9
. Classes in Files
If a class is longer than 
2
 pages of code then it
should be saved in its own Java text file.
There should not be more than 
3
 classes in a single
Java text file.
Having multiple files makes it easier to find code,
and (re-)compilation is quicker.
continued
18
I use Windows Grep to search for text 
inside
multiple files (and directories)
free from 
http://www.wingrep.com
19
2
.  Method-related Guidelines
2.1.  Method Names
2.2.  Method Visibility
2.3.  Method Length
2.4.  Keep Anonymous Classes Small
20
2.1
. Method Names
A method name should have the form 
verbNoun(…)
e.g. 
makeGraph()
, 
printFile()
Comments should not ‘echo’ the method name:
 
private void makeGraph()
// make the graph
{ ... }
useless since
it adds no new
information
21
2.2
. Method Visibility
Methods should be 
private
 
unless they will be
called from outside the object.
In basic Java programming, you will not need to use
the 
protected
 
keyword.
22
2.3
. Method Length
No method should be longer than 
1
 page of print-out
e.g. large constructor methods are bad
No method should be smaller than 
5
 lines
except
 for 
main()
 which should be as small as possible
23
2.4
. Keep Anonymous Classes Small
An anonymous class inside a method should be less
than 
10
 lines long.
A separate handler class is better style for large size
listener code.
24
3
.  Comment-related Guidelines
3.1.  Project Details
3.2.  Project Overview
3.3.  Class/Method Comments
3.4.  Other People’s Code
3.5.  Line Comments
3.6.  Comment Style
25
3.1
. Project Details
The top-level class is your program must start with
project details
:
subject number, subject name
project title
student name, student number, student e-mail
date when project finished (submitted)
continued
26
3.2
. Project Overview
The top-level class is your program must include an
overview
 of the project.
About 
1/2
 - 
1
 page of text, made up of:
3-5
 lines explaining the project;
lines explaining how to compile and 
run 
the program
;
lines explaining program input and output
27
3.3
. Class/Method Comments
Each 
class
 must start with 
5-15
 lines explaining what it
does.
Each 
complex method
 should have 
1-5
 lines of
comments at the beginning, saying what it does.
28
3.4
. Other People’s Code
If you use (or modify) someone’s code, then you must
include comments giving:
the name of the original class/method;
the author’s name;
where the class/method is from (e.g. a URL);
when you obtained (downloaded) the class/method;
how
 you modified the class/method
29
3.5
. Line Comments
Complex pieces of code inside a method should be
commented with
 
//
 
// calculate the Von Krotsberg value
double vk = x * (y-1) * (y-1);
Put the comment on a line above the code, or following
the code on the same line.
30
3.6
. Comment Style
Do not surround a comment with lots of rubbish. e.g.
 
/******************************
******++++++++++++++++++*******
******   method getBalance() **
*******************************/
public int getBalance()
{ return balance; )
most (all) of this
can be deleted
31
4
. Layout-related Guidelines
4.1
.  Avoid the “Tab” Key
4.2
.  Use Good Code Layout
4.3
.  Wrap-around Lines
4.4.   Use a Java code Formatter (perhaps)
4.5
.  Don’t Waste Trees
4.6
.  Print-out Style
32
4.1
. Avoid the “Tab” Key
Do not tab
 to indent code:
 
private int foo()
{
 
if (x < 
2
) {
   
if (y > 
4
) {
    
if ( z != 
5
) {
     
x = 
1
;
    
:
}
the code
disappears
off the screen
and print-out
continued
Tab key 
pressed
BAD
33
Instead, use 
two
 spaces for 
a "
tab
"
:
 
int foo()
{  if (x < 
2
) {
     if (y > 
4
) {
       if ( z != 
5
) {
         x = 
1
;
           :
}
continued
space key 
pressed
GOOD
34
4.2
. Use Good Code Layout
Bad
 
layout example:
 
if (x<
2
) x++; else {y++; x--}
Look in text books for examples of good layout (or in
my 
code examples
).
35
4.3
.  Wrap-around Lines
A 
wrap-around line
 is a very long line of code that
goes off the right edge of the screen and starts
again on the next line.
 They are 
BAD
.
These lines are hard to read, and when the code is
printed, the wrap-around part may not appear.
Reformat the line to be several shorter lines.
36
4.4.  Use a Java code Formatter
I sometimes use a source code formatter called 
jacobe
to help me format Java code.
A free version for Windows is available at:
http://www.tiobe.com/jacobe.htm
But
, changing its default output requires the editing of
a large configuration file.
(perhaps)
continued
37
38
4.5
. Don
'
t Waste Trees
Print two pages of code onto a single sheet of A
4
this will half the amount of paper you use
FinePrint is a printer driver that will do this for most
printers
get it from 
http://www.fineprint.com
continued
39
40
4.6
. Print-out Style
In Windows, programs should be 
types 
using 
10
point Courier New
. e.g.:
  
hello from Andrew
Print in pure black and white (i.e. no grey scales)
colour is acceptable, but not required
continued
41
If your text editor allows it, include the date, time, and
page numbers in the print-out.
I use the 
Notepad++
 text editor, free from
http://notepad-plus-plus.org/
has a Thai language pack
continued
42
continued
43
Do 
not
 write on the print-out using a pen or pencil.
Do 
not
 put the print-out in a plastic envelope
and/or binder.
Do
 s
taple the pages of the print-out together at the
top-left hand corner.
44
5
.  More Information
A great book on coding style (for any language, not
just Java):
Code Complete
Steve McConnell
Microsoft Press, 
2
nd ed., 
2004
http://cc
2
e.com/
45
Slide Note
Embed
Share

In this document, you will find comprehensive guidelines for good Java coding practices. Covering important aspects such as naming conventions for classes and objects, handling class data, using static for constants, initializing variables, and minimizing global variables. Following these guidelines will help ensure consistency and readability in your Java projects.

  • Java
  • Coding Style
  • Guidelines
  • Programming

Uploaded on Feb 19, 2025 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. DIN61-222 Adv. Prog. (Java) Semester 1, 2019-2020 16. Coding Style Objectives to give guidelines for good Java coding I use these guidelines when marking projects, exams, etc. 1

  2. Overview 1. Class-related Guidelines 2. Method-related Guidelines 3. Comment-related Guidelines 4. Layout-related Guidelines 5. More Information 2

  3. 1. Class-related Guidelines 1.1. Class Names 1.2. Object Names 1.3. Class Data 1.4. Static for Constants 1.5. Initializing Variables 1.6. Few Global Variables 1.7. Get and Set 1.8. Change Date Locally 1.9. Classes in Files 3

  4. 1.1. Class Names A class name should be a noun the noun is often a "type-of-thing" word starts with an uppercase letter e.g. Plane, Car, Database long names may use several words e.g. JumboJet, Toyota, StudentDb each word starts with an uppercase letter 4

  5. 1.2. Object Names An object name should be a noun the noun is often the class word and a number e.g. plane1 car2, database5 but try to use names with more meaning e.g. andrewDb, coeCar starts with a lowercase letter 5

  6. 1.3. Class Data Always define data as private e.g. private int x; Avoid the keywords public, protected Always include a visibility keyword e.g.int x; // bad: unclear 6

  7. 1.4. Static for Constants Only use staticto declare constants: private static final int MAXLEN = 120; always write static final always write the constant name in all uppercase (Almost) never use staticwith methods (except for main()) 7

  8. 1.5. Initializing Variables Global objects and variables should be initialised inside a method (often the constructor): private int counter; // global public Matrix() { counter =0; } It may be okay to initialise simple global variables (e.g. ints, doubles) globally: private int counter =0; // global 8

  9. 1.6. Few Global Variables Keep the number of global variables in a class to a minimum. BadCode: private int x; // global in class public void calc() { x =0; bar(5); System.out.println(x); } private void bar(int y) { x = x + y; } continued9

  10. The code is bad because a person who looks at a class will need to check every line of code to find out where x is used. The use of globals often means that a student is not sure how to change variables or objects inside Java methods continued10

  11. the global x has gone Good Code: public void calcX() { int x =0; x = addX(x,5); // x gets new value System.out.println( x= + x); } private int addX(int x, int y) { return x+y; } x in addX() is a copy of the x in calcX() continued 11

  12. The code is better since x is local to the method that uses it, and is passed as a parameter to the other method Note how x is updated by using return the following code will not change x in calcX(): private void addX(int x, int y) { x = x+y; } continued12

  13. Good code with objects: public void calcMatrix() { Matrix m1 = new Matrix(); processMatrix(m1); m1.print(); } objects are passed using call-by-reference, so do not need to be returned private void processMatrix(Matrix m) { // change m (really m1) } 13

  14. 1.7. Get and Set Private data which will be accessible outside an object should be given setand getmethods public class BankAccount { private double balance; public double getBalance() { return balance; } public void setBalance(double b) { balance = b; } : } continued14

  15. The method names must be set<Variable> and get<Variable>. Only include a setmethod if the variable needs to be changed. 15

  16. 1.8. Change Data Locally Methods that change data should be in the class where the data is declared. Badcode: public static void main(String args[]) { BankAccount myacc = new BankAccount(); double bal = myacc.getBalance(); bal = bal * 1.15; // calculate interest myacc.setBalance(bal); } balchange is done in main() continued 16

  17. Good code (in BankAccount): public void applyInterest(double interest) { bal = bal * interest; } in main(): BankAccount myacc = new BankAccount(); myacc.applyInterest(1.15); balchange done in the BankAccount object 17

  18. 1.9. Classes in Files If a class is longer than 2 pages of code then it should be saved in its own Java text file. There should not be more than 3 classes in a single Java text file. Having multiple files makes it easier to find code, and (re-)compilation is quicker. continued18

  19. I use Windows Grep to search for text inside multiple files (and directories) free from http://www.wingrep.com 19

  20. 2. Method-related Guidelines 2.1. Method Names 2.2. Method Visibility 2.3. Method Length 2.4. Keep Anonymous Classes Small 20

  21. 2.1. Method Names A method name should have the form verbNoun( ) e.g. makeGraph(), printFile() Comments should not echo the method name: private void makeGraph() // make the graph { ... } useless since it adds no new information 21

  22. 2.2. Method Visibility Methods should be privateunless they will be called from outside the object. In basic Java programming, you will not need to use the protectedkeyword. 22

  23. 2.3. Method Length No method should be longer than 1 page of print-out e.g. large constructor methods are bad No method should be smaller than 5 lines except for main() which should be as small as possible 23

  24. 2.4. Keep Anonymous Classes Small An anonymous class inside a method should be less than 10 lines long. A separate handler class is better style for large size listener code. 24

  25. 3. Comment-related Guidelines 3.1. Project Details 3.2. Project Overview 3.3. Class/Method Comments 3.4. Other People s Code 3.5. Line Comments 3.6. Comment Style 25

  26. 3.1. Project Details The top-level class is your program must start with project details: subject number, subject name project title student name, student number, student e-mail date when project finished (submitted) continued26

  27. 3.2. Project Overview The top-level class is your program must include an overview of the project. About 1/2 - 1 page of text, made up of: 3-5 lines explaining the project; lines explaining how to compile and run the program; lines explaining program input and output 27

  28. 3.3. Class/Method Comments Each class must start with 5-15 lines explaining what it does. Each complex method should have 1-5 lines of comments at the beginning, saying what it does. 28

  29. 3.4. Other Peoples Code If you use (or modify) someone s code, then you must include comments giving: the name of the original class/method; the author s name; where the class/method is from (e.g. a URL); when you obtained (downloaded) the class/method; how you modified the class/method 29

  30. 3.5. Line Comments Complex pieces of code inside a method should be commented with// // calculate the Von Krotsberg value double vk = x * (y-1) * (y-1); Put the comment on a line above the code, or following the code on the same line. 30

  31. 3.6. Comment Style Do not surround a comment with lots of rubbish. e.g. /****************************** ******++++++++++++++++++******* ****** method getBalance() ** *******************************/ public int getBalance() { return balance; ) most (all) of this can be deleted 31

  32. 4. Layout-related Guidelines 4.1. Avoid the Tab Key 4.2. Use Good Code Layout 4.3. Wrap-around Lines 4.4. Use a Java code Formatter (perhaps) 4.5. Don t Waste Trees 4.6. Print-out Style 32

  33. 4.1. Avoid the Tab Key Do not tab to indent code: private int foo() { if (x < 2) { } the code disappears off the screen and print-out if (y > 4) { if ( z != 5) { : BAD Tab key pressed x = 1; continued 33

  34. Instead, use two spaces for a "tab": int foo() { if (x < 2) { if (y > 4) { if ( z != 5) { x = 1; : } pressed space key GOOD continued 34

  35. 4.2. Use Good Code Layout Badlayout example: if (x<2) x++; else {y++; x--} Look in text books for examples of good layout (or in my code examples). 35

  36. 4.3. Wrap-around Lines A wrap-around line is a very long line of code that goes off the right edge of the screen and starts again on the next line. They are BAD. These lines are hard to read, and when the code is printed, the wrap-around part may not appear. Reformat the line to be several shorter lines. 36

  37. 4.4. Use a Java code Formatter (perhaps) I sometimes use a source code formatter called jacobe to help me format Java code. A free version for Windows is available at: http://www.tiobe.com/jacobe.htm But, changing its default output requires the editing of a large configuration file. continued37

  38. 38

  39. 4.5. Don't Waste Trees Print two pages of code onto a single sheet of A4 this will half the amount of paper you use FinePrint is a printer driver that will do this for most printers get it from http://www.fineprint.com continued39

  40. 40

  41. 4.6. Print-out Style In Windows, programs should be types using 10 point Courier New. e.g.: hello from Andrew Print in pure black and white (i.e. no grey scales) colour is acceptable, but not required continued41

  42. If your text editor allows it, include the date, time, and page numbers in the print-out. I use the Notepad++ text editor, free from http://notepad-plus-plus.org/ has a Thai language pack continued42

  43. continued43

  44. Do not write on the print-out using a pen or pencil. Do not put the print-out in a plastic envelope and/or binder. Do staple the pages of the print-out together at the top-left hand corner. 44

  45. 5. More Information A great book on coding style (for any language, not just Java): Code Complete Steve McConnell Microsoft Press, 2nd ed., 2004 http://cc2e.com/ 45

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#