Publications: 106 | Followers: 1


Publish on Category: Birds 0

Logger, Assert and Invariants
Debugging is afact of life.Arise for many reasons (typing mistakes, conceptual errors).What can we do to make it easier?Some IDEs havetools.We can useLoggingandassertstatements.
To debug use Logging
When debugging we can insertprint statementsinto the program andprint out values of variables.Thisinformstheprogrammerwhat is happening inside the program as it runs.However, then you need todeleteorcomment outall the print statements.Logging is a better way.
Package and Name
Thejava.util.loggingpackage 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.
Levels of Logging
A main method
public static void main(Stringargv[]) {System.out.println("fLogger.getName() = " +fLogger.getName());//System.out.println("fLogger2.getName() = " + fLogger2.getName());fLogger.setLevel(Level.INFO);callAllLevels();fLogger.setLevel(Level.WARNING);callAllLevels();fLogger.setLevel(Level.SEVERE);callAllLevels();fLogger.setLevel(Level.OFF);callAllLevels();}
What is printeddepends on the level
public static voidcallAllLevels() {System.out.println("fLogger.getLevel() = " +fLogger.getLevel());"this is info");fLogger.warning("this is a warning");fLogger.severe("this is severe");System.out.println("");}
From Now, for debugging
Do not use printingto debug code –printing is for printing.Define a logger for each class(but you can and might like to define more!).When you aredebuggingturn thelogger level to “ALL”When you havefinisheddebugging turn thelogger level to “OFF”
Motives of Assertions
Anassertionis a statement inJavathatenables you to test yourassumptionsabout yourprogram (data).For example, if you write a method that calculates thespeed of a particle, you might assert that the calculated speed is less thanthe speed of light. (other examples???)
Each assertion contains aBooleanexpressionthat youbelieve will be truewhen the assertion executes.the assertionconfirms your assumptionsabout thebehaviourof yourprogramExperience has shown that writing assertions while programming isone of the quickest and most effective ways to detect and correct bugs.
Assert Syntax
assertkeyword is used to implement assertion in java. we can use assert keyword in two formatassertbooleanExpression;assertbooleanExpression:errorMessage;assertbooleanExpression: “”;//same as first
Do not catch
You should not encounter anyAssertionErrorsthrough normal execution of a properly written program.Sucherrors should onlyindicate bugsin the implementation.Asa result, you shouldnever catchanAssertionError.
Assert Example
Scanner input =new Scanner(;System.out.print("Enter a number between 0 and 10: ");intnumber =input.nextInt();assert (number >= 0 && number <= 10) : "bad number: " + number;System.out.printf("You entered %d\n", number);input.close();
Code – line by line
1// Fig. 13.9: AssertTest.java2// Demonstrates the assert statement3importjava.util.Scanner;45public classAssertTest6{7public static void main( Stringargs[] )8{9Scanner input = new Scanner( );1011System.out.print( "Enter a number between 0 and 10: " );12intnumber =input.nextInt();1314// assert that the absolute value is >= 015assert ( number >= 0 && number <= 10 ) : "bad number: " + number;1617System.out.printf( "You entered %d\n", number );18} // end main19} // end classAssertTest
Run and Compile
To run the above example,Compile the example with:javacAssertionExample.javaRun the example with:java-eaAssertionExampleTo enable assertions at runtime,  -eacommand-line option is used
Examples ofInvariants
Pythagoras(from maths).Conservation ofEnergy(from physics)Can you think of any others…?Conservationslaws, andtheoremsare just different names forinvariants(there is a subtle difference).Ripples on a pond/ladder against a wall.
Benefit of using Assertion in Java
Assertionis simply great fordata validation.Assertionin Javaguaranteesthat at a certain point yourassumption, this makesdebugging in Javalot easier.UsingJava assert keyword helps todetect bugearly in development cycle which is verycost effective.Writingcode withassert statementwill help you to be better programmer andimprove quality of code.Assertionin java gives you lot ofconfident while maintaining or refactoring code.
Important point about Java assertion
1) Assertion is introduced inJDK1.4 and implemented usingassertkeyword in java.2) assertion can beenableanddisableat runtime3) Always rememberAssertiondoes notreplaceExceptionbutcomplimentsit.4) Assertion also doesn't replace need ofunit testing.5) Do not useassertionto validate arguments or parameters ofpublic method.
Exceptionsare the customary way in Java to indicate to a calling method that anabnormal conditionhasoccurredyoumust position catchers (the exception handlers)strategically, so your program will catch and handle all exceptions from which you want your program torecover.
Assert or Exception
Assertionsshould be used to check something thatshould never happen, while anexceptionshould be used to check something thatmight happen.Throwing anExceptionis a way to deal withexternal problems(wrong sort of data coming in).Assert is to check your data yourself (you can enable and disable assertions –ea)Look atpre-andpost conditionsof a method, what are theinvariants.Design by contract.
Assertionsshould be used to check something thatshould never happen, while anexceptionshould be used to check something thatmay happen.afunction mightdivide by 0, so anexception should be used, but anassertioncould be used to check that thehard-drivesuddenlydisappears.Anassertionwould stop the program from running, but anexception would let the program continue running.
use exceptions…
whenchecking parameters passed topublic or protected methods and constructorswheninteracting with the useror when you expect theclient codetorecoverfrom anexceptional situationto addressproblems that might occur
use assertions…
whencheckingpre-conditions, post-conditionsandinvariantsofprivate/internal codeto providefeedbacktoyourselfor yourdeveloper teamwhen checking for things that are very unlikely to happen otherwiseit means that there is a serious flaw in your applicationtostate thingsthatyou (supposedly) knowto betrue
-ea(enable assertions)
Remember assertions can be disabled at runtime using parameters, andare disabled by default, so don't count on them except for debugging the argument to enable assertions.You can think of this as a debug mode.Always remember Assertion does not replace Exception but compliments it.





Make amazing presentation for free