Presentation is loading. Please wait.

Presentation is loading. Please wait.

Logger, Assert and Invariants

Similar presentations


Presentation on theme: "Logger, Assert and Invariants"— Presentation transcript:

1 Logger, Assert and Invariants

2 Debugging Debugging is a fact of life.
Arise for many reasons (typing mistakes, conceptual errors). What can we do to make it easier? Some IDEs have tools. We can use Logging and assert statements.

3 To debug use Logging When debugging we can insert print statements into the program and print out values of variables. This informs the programmer what is happening inside the program as it runs. However, then you need to delete or comment out all the print statements. Logging is a better way.

4 Package and Name The java.util.logging package provides the logging capabilities via the Logger class. It is common practice to use the fully qualified name of each class whose activity is being logged as a message category because this allows developers to fine-tune log settings for each class.

5 Levels of Logging We will just use 3 levels to start. INFO WARNING
SEVERE We can display INFO, WARNING, SEVERE WARNING, SEVERE

6 A main method public static void main(String argv[]) { System.out.println("fLogger.getName() = " + fLogger.getName()); //System.out.println("fLogger2.getName() = " + fLogger2.getName()); fLogger.setLevel(Level.INFO); callAllLevels(); fLogger.setLevel(Level.WARNING); fLogger.setLevel(Level.SEVERE); fLogger.setLevel(Level.OFF); }

7 What is printed depends on the level
public static void callAllLevels() { System.out.println("fLogger.getLevel() = " + fLogger.getLevel()); fLogger.info("this is info"); fLogger.warning("this is a warning"); fLogger.severe("this is severe"); System.out.println(""); }

8 From Now, for debugging Do not use printing to debug code – printing is for printing. Define a logger for each class (but you can and might like to define more!). When you are debugging turn the logger level to “ALL” When you have finished debugging turn the logger level to “OFF”

9 Motives of Assertions An assertion is a statement in Java that enables you to test your assumptions about your program (data). For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light. (other examples???)

10 Assert Each assertion contains a Boolean expression that you believe will be true when the assertion executes. the assertion confirms your assumptions about the behaviour of your program Experience has shown that writing assertions while programming is one of the quickest and most effective ways to detect and correct bugs.

11 Assert Syntax assert keyword is used to implement assertion in java. we can use assert keyword in two format assert booleanExpression; assert booleanExpression : errorMessage; assert booleanExpression : “”;//same as first

12 Do not catch You should not encounter any AssertionErrors through normal execution of a properly written program. Such errors should only indicate bugs in the implementation. As a result, you should never catch an AssertionError.

13 Assert Example Scanner input = new Scanner(System.in); System.out.print("Enter a number between 0 and 10: "); int number = input.nextInt(); assert (number >= 0 && number <= 10) : "bad number: " + number; System.out.printf("You entered %d\n", number); input.close();

14 Code – line by line 1 // Fig. 13.9: AssertTest.java 2 // Demonstrates the assert statement 3 import java.util.Scanner; 4 5 public class AssertTest 6 { 7 public static void main( String args[] ) 8 { 9 Scanner input = new Scanner( System.in ); System.out.print( "Enter a number between 0 and 10: " ); 12 int number = input.nextInt(); // assert that the absolute value is >= 0 15 assert ( number >= 0 && number <= 10 ) : "bad number: " + number; System.out.printf( "You entered %d\n", number ); 18 } // end main 19 } // end class AssertTest

15 Run and Compile To run the above example, Compile the example with: javac AssertionExample.java Run the example with: java -ea AssertionExample To enable assertions at runtime, -ea command-line option is used

16 Examples of Invariants
Pythagoras (from maths). Conservation of Energy (from physics) Can you think of any others…? Conservations laws, and theorems are just different names for invariants (there is a subtle difference). Ripples on a pond/ladder against a wall.

17 Benefit of using Assertion in Java
Assertion is simply great for data validation. Assertion in Java guarantees that at a certain point your assumption, this makes debugging in Java lot easier.  Using Java assert keyword helps to detect bug early in development cycle which is very cost effective.  Writing code with assert statement will help you to be better programmer and improve quality of code.  Assertion in java gives you lot of confident while maintaining or refactoring code.

18 Important point about Java assertion
1) Assertion is introduced in JDK 1.4 and implemented using assert keyword in java. 2) assertion can be enable and disable at runtime   3) Always remember Assertion does not replace Exception but compliments it. 4) Assertion also doesn't replace need of unit testing. 5) Do not use assertion to validate arguments or parameters of public method.

19 Exceptions Exceptions are the customary way in Java to indicate to a calling method that an abnormal condition has occurred you must position catchers (the exception handlers) strategically, so your program will catch and handle all exceptions from which you want your program to recover.

20 Assert or Exception Assertions should be used to check something that should never happen, while an exception should be used to check something that might happen. Throwing an Exception is a way to deal with external problems (wrong sort of data coming in). Assert is to check your data yourself (you can enable and disable assertions –ea ) Look at pre- and post conditions of a method, what are the invariants. Design by contract.

21 Assertions should be used to check something that should never happen, while an exception should be used to check something that may happen. a function might divide by 0, so an exception should be used, but an assertion could be used to check that the hard-drive suddenly disappears. An assertion would stop the program from running, but an exception would let the program continue running.

22 use exceptions… when checking parameters passed to public or protected methods and constructors when interacting with the user or when you expect the client code to recover from an exceptional situation to address problems that might occur

23 use assertions… when checking pre-conditions, post-conditions and invariants of private/internal code to provide feedback to yourself or your developer team when checking for things that are very unlikely to happen otherwise it means that there is a serious flaw in your application to state things that you (supposedly) know to be true

24 -ea (enable assertions)
Remember assertions can be disabled at runtime using parameters, and are disabled by default, so don't count on them except for debugging purposes. java -ea AssertTest -ea is the argument to enable assertions. You can think of this as a debug mode. Always remember Assertion does not replace Exception but compliments it.


Download ppt "Logger, Assert and Invariants"

Similar presentations


Ads by Google