1 Java coding conventions Lecture 2. 2 Please read Not only on assignment 1, but always. 80% of the...

31
1 Java coding conventions Lecture 2

Transcript of 1 Java coding conventions Lecture 2. 2 Please read Not only on assignment 1, but always. 80% of the...

Page 1: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

1

Java coding conventions

Lecture 2

Page 2: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

2

Please read http://Java.sun.com/docs/codeconv/index.html Not only on assignment 1, but always.

• 80% of the lifetime cost of a piece of software goes to maintenance.

• Hardly any software is maintained for its whole life by the original author.

• Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.

• If you ship your source code as a product, you need to make sure it is as well packaged and clean as any other product you create.

Page 3: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

3

The javadoc tool

… generates HTML documentation directly from doc comments in your Java source code.• /* * Not a doc comment */•/** * A doc comment */

Page 4: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

4

Javadoc example package examples.intro;

/** * class to demonstrate assert facility of J2SDK v1.4 */public class AssertTester { /** * main method of AssertTester prints program * arguments to <code>System.out</code> * @param args[] command line arguments * @throws java.lang.AssertionError * occurs if no argument are supplied * or an argument has more than 3 characters */ public static void main(String[] args) { . . . }}

Page 5: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

5

Other comments

Line comment•// blabla til end of line•java code // blabla til eol

Block comment•/* blabla */•/* blabla */

Page 6: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

6

Common Javadoc tags

@param variable_name description• @param args[] command line arguments

• @param index index number of element. 1<=index.

@return description• @return maximum value of the two parameters

@throws complete_classname description• @throws com.ifor.util.FallIntoLakeException blablabla

See page 27-30 in the book.

Page 7: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

7

Contained classes

Lecture 2

Page 8: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

8

Enclosed classes

A class may be defined inside the definition of another class

Depending on how it is defined, it falls into one of 4 categories• Nested top-level class

• Member inner class

• Local inner class

• Anonymous local inner class

Page 9: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

9

Nested top level class

are declared with the keyword static. Although it is contained within another

class, it has the same behavior as ordinary top-level classes.

It is just an alternative grouping method similar to a package.

Page 10: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

10

Nested top level class example public class Graph1 {

public void addNode( int x, int y ) { Node n = new Node( x, y ); }

public static void main( String[] args ) { Graph1 g = new Graph1(); g.addNode( 4, 5 ); g.addNode( -6, 11 ); }

private static class Node { private int x, y;

public Node( int x, int y ) { this.x = x; this.y = y; } } // end of Node class

} // end of Graph1 class

Page 11: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

11

Member inner class

Not declared as static. Must be instantiated as part of an instance of

their enclosing class. •Enclosing e = new Enclosing();Inner i1 = e.new Inner();Inner i2 = e.new Inner();/* i1 and i2 both has access to members in e */

A member inner class is a qualified member of the enclosing class

Page 12: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

12

Local inner classes

Are defined within a method. Their definition is private to that method. But they have full access to the

members of the enclosing class

Page 13: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

13

Local inner classes Example public class Equation2 {

<<blabla>>

public Result getResult( final int input1, final int input2 ) { final int[] localVar = { 2,6,10,14}; return new Result() { private int normalField;

public double getAnswer() { return (double) input1/input2 - normalField; } // this is an instance initializer block { normalField = 2; } }; }}

Page 14: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

14

Anonymous inner classes

Are local inner classes that do not have a name.

Are created with the enhanced syntax of the new keyword.• New [class_name()] {body_of_class}

Page 15: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

15

Read more in the book

In Chapter 2 Sooner or later you will encounter code

that exploits nested and inner classes.

Page 16: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

16

Exceptions

Lecture 2

Page 17: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

17

Basic pattern for handling Exceptions try{ doSomething(); somethingMore(); evenMore();} catch (someException e) { bla();} catch (otherException e) { bla(); bla();} finally { always();}

Page 18: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

18

Checked / Unchecked

Exception• Most Exceptions must be handled (i.e. either

declared in the method’s throws clause or caught)

• Except Runtime Exceptions, which are “unchecked” – they don’t have to be declared

Page 19: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

19

Two ways To throw:<<return_type>> <<method_name>>(<<args>>) throws <<ExceptionType>> { <<calls to methods that have declared Exceptions in their throws

clauses are in the body of this method.>> }

To catch:<<return_type>> <<method_name>>(<<args>>) { try {

<<calls to methods that have declared Exceptions in their throws clauses are in the body of this try statement.>>

} catch (<<ExceptionType>> <<exceptionVariableName>>) { <<here you can report the exception, and recover from it.>> }}

Page 20: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

20

When to do what?

If code that your code calls declares that it can throw an Exception, what should you do?• Just throw the exception

• Catch the exception, report it, and recover

• Catch the exception, make a new, different exception, and throw the new one

When do you throw an Exception even if no Exception was thrown to you?

Page 21: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

21

When to re-throw the Exception

If it’s more appropriate to deal with it at a higher level of the code.

If the exception means death to the method it’s in. In other words, there’s no reasonable way you can continue to execute the code of this method.

Page 22: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

22

When to catch it and recover

If this is the appropriate place to report the exception to the user, or log it, or whatever you plan to do with it.

If you can and should continue with this method – for example if you can use a default value, or try again.

Page 23: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

23

When to catch it & throw your own

If you’re sure the Exception is impossible (your code is correct), so you don’t want to have to declare it all the way up.

On the other hand, if your code is incorrect, you should not “hide” the exception – you need to see it so that you can fix your programmer error. Throw a new RuntimeException, or your own sub class of RunTimeException.

Page 24: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

24

When to create your own Exception

Sometimes you might create a new Exception instance even though none of your code threw one to you. You might be the first “thrower” of this Exception.

You should do this if your code detects some error state that you cannot recover from in this method – for example, an input might be of an illegal value.

Page 25: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

25

Use of Exceptions

When handling critical events that may jeopardize the system stability or worse.• Obvious

Feedback to the caller• Should we throw an Exception when the user

inputs data with wrong syntax?

• What’s your point of view?

• Depends on the context?

• Is the fine line fuzzy and gray again?

Page 26: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

26

Checked or Unchecked? If you create your own new Exception class, should it

be checked or Runtime? RuntimeExceptions are for programmer error

• i.e. your code is in a bad state. Stop program execution and go debug. By the time a program reaches an end-user, it should never throw these. The outermost layer of your program should gracefully catch all Exceptions, even Runtimes and do something user-friendly.

Checked exceptions (all except RuntimeExceptions) are for dealing with the outside world. • If something about the input the user gave you is bad, or a file

is corrupt, or a database server is down, these are real-life things that could happen, and your program should cope with them as gracefully as possible.

Page 27: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

27

Summary of Exceptions

Catch and hide an exception if• Can recover: (default value, user try again)

Re-throw an exception if• Irrecoverable to method

• More appropriate to handle elsewhere

Throw new if• You receive a checked exception and want to

throw an unchecked runtime exception

Page 28: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

28

Summary of Exceptions

When creating your own exception class• Name it descriptively

• Place appropriately in class heirarchy

• If programmer error, make it a subclass of RuntimeException (so it’s unchecked)

• If outside error (network, user, etc.), make it a checked Exception

Page 29: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

29

Assignment 1

Lecture 2

Page 30: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

30

getMethods() ?

Question yesterday:• Why does getMethods() return many methods

when the class contain no methods at all?

Read the API documentation for that method thoroughly and you will find out. Or even ask your peers, but not immediatelly. (and mention it in the report if the help was significant).

Page 31: 1 Java coding conventions Lecture 2. 2 Please read  Not only on assignment 1, but always. 80% of the lifetime.

31

Interfaces

What constitutes a constant field in an interface?• “Every field declaration in the body of an interface is

implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.”

• From the language specification. The assignment specification tells us what

fields to consider “constant”, and thus to be included in the interface:• “final”