Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations

Presentation on theme: "1 Java coding conventions Lecture 2. 2 Please read Not only on assignment 1, but always. 80% of the lifetime."— Presentation transcript:

1 1 Java coding conventions Lecture 2

2 2 Please read 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.

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

4 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 System.out * @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) {... } }

5 5 Other comments Line comment // blabla til end of line java code // blabla til eol Block comment /* blabla */

6 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.

7 7 Contained classes Lecture 2

8 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

9 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.

10 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

11 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 = Inner(); Inner i2 = Inner(); /* i1 and i2 both has access to members in e */ A member inner class is a qualified member of the enclosing class

12 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

13 13 Local inner classes Example public class Equation2 { > 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; } }; } }

14 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}

15 15 Read more in the book In Chapter 2 Sooner or later you will encounter code that exploits nested and inner classes.

16 16 Exceptions Lecture 2

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

18 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

19 19 Two ways To throw: > >( >) throws > { > } To catch: > >( >) { try { > } catch ( > >) { > }

20 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?

21 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.

22 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.

23 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.

24 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.

25 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?

26 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.

27 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

28 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

29 29 Assignment 1 Lecture 2

30 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).

31 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”

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

Similar presentations

Ads by Google