Go Back   TechArena Community > ARENA > Guides & Tutorials
Become a Member!
Forgot your username/password?
Register Tags Active Topics RSS Search Mark Forums Read SiteMap

Tags: , , , ,

Sponsored Links



Assertions in Java

Guides & Tutorials


Reply
 
Thread Tools Search this Thread
  #1  
Old 25-02-2010
Member
 
Join Date: Feb 2010
Posts: 136
Assertions in Java

Assertions in Java


1. Introduction:
1.1 What is an Assertion:
In English assertion means moving forward as true. By this it is quit clear definition, but in terms of an programming language like java it does not has a exact definition.

Lest start with a small example
Code:
/**
     * Checking the equality of two ints.<p>
     * Check that the two ints are well simply by comparing equivalent
     * The start date and end date.
     * @ return true if the two ints are equivalent.
     */
    Public boolean equals (java.lang.Object obj) (
        if (null == Obj) ( / / Nothing to compare
            return false;
        }
        if (! (Obj instanceof dtinter)) ( / / The wrong type of object
            return false;
        }
        dtinter int = (dtinter) obj;

        / / From this point, we know that we can begin some tests
        / / As again, we take care of setters, there is more to resume
        / / Code start
        return getBeginAt (). equals (intle.getBeginAt ()) & & getEndAt (). equals (intle.getEndAt ());)
There are three lines that attract the attention, they are the comments in the middle of code. In the form of comments getBeginAt () and getEndAt () never return null. Well, fine, but there could be a syntax that comes specify the same thing, and that includes the compiler.

Code:
  /**
     * Checking the equality of two ints.<p>
     * Check that the two ints are well simply by comparing equivalent
     * The start date and end date.
     * @ return true if the two ints are equivalent.
     */
    Public boolean equals (java.lang.Object obj) (
        if (null == Obj) ( / / Nothing to compare
            return false;
        }
        if (! (Obj instanceof dtinter)) ( / / The wrong type of object
            return false;
        }
        dtinter int = (dtinter) obj;

        assert null! getBeginAt = ();
        assert null! getEndAt = ();

        return getBeginAt (). equals (intle.getBeginAt ()) & & getEndAt (). equals (intle.getEndAt ());
    }
Here we go, I said the same thing with the comments but this time the compiler is able to interpret especially if someone were to amend the Code as accessors and forgets or ignores the existence. This constraint will be notified of the error very fast. It will not spend hours looking for where its just bug. In addition, I gained clarity since the assertions are easier to read than the sentence three lines.
Reply With Quote
  #2  
Old 25-02-2010
Member
 
Join Date: Feb 2010
Posts: 136
Re: Assertions in Java

2. Syntax:
Assertions and their use in java. The assert keyword is used so as follows:
Code:
assert condition [: object];
where condition is a conditional expression is to say anything with the return value is a boolean and object is any object containing information about the failure of the assertion.
Most of the time, so you use the following syntax :
Code:
mycondition assert (): "My condition should always be checked before ....";
assert size () <5: "The car can not have more than 4 wheels";
Thanks to this little snippet nothing at all, your development will really be improved. But beware, it's like everything, does not solve everything to assert at once, or you'll fall in excess regrettable. If you think this is complicating then just read it for time being and go on reading further , you will understand the means to this when you will start doing some hand on programs.

3. Use:
So how and where to use these especially famous assertion? Well, to start whenever you assume a truth without it is trivial, say almost every time you assume something in the code, write it in an assert. To clearer, I mean, whenever you are in the situation that I presented in the introduction.

3.1. Logical Invariant:
The logical constants are all constants for which logical semantics of previous code leads what appears to be a topology when we wrote but could it be destroyed in the future modification of this code. As you presumed fact of a truth that is not translated by code, it is good to specify by an assertion. How? Can this sound complicated? So, as always, a example and you will immediately start understanding

Code:
lgin = (x * x) / (1 + (X * x));
assert lgin < 1  : "lgin Coefficient is between 0 and 1";
assert 0 <= Coef: "lgin Coefficient is between 0 and 1";


3.2. Invariant Flow Control:

The flow controls are essential for the smoothing your programs. No assertion is that you reread your code are able to tell if the stream is followed, or if it is bad quality. With the notion of assertion, you can ask your computer to the Control Flow for you, and I can assure you that when these flows are becoming numerous. In your code, there are points where you are sure you do not have or spend time under specific conditions. If for example I make sure that the user can not choose option off values I present him with a combo-box, and I am when I code, certain to find in a table an object corresponding to one of these values, I have to only make a loop that looks for value and makes a return from it was found. Here is an example of this
Code:
/**
         * Estimate the price passed as argument.<p>
         * <are color="red">Note this code can not be considered
         * Sturdy, it is stripped of everything that does not directly 
         * Demonstration in progress: control flow using an assertion. Use
         * Tables instead of collections is not a good practice
         * But it helps to focus attention on the purpose of the demonstration</are><p>
         * Builds on two tables of same length containing the foundations of price and
         * Associated estimates.
         * @ param Price Price in Country
         * @ return A string containing the estimate of the computer
         * @ Throw IllegalArgumentException if the price is negative
         */
        Public String controleDeFlux (int price) throws IllegalArgumentException (

                if (price < 0) { / / The price can not be negative
                        throw IllegalArgumentException ("The price is negative");
                }

                int min = 0;

                for(int i =0; I <tbprix.length; i + +) (
                        if ((low <= price) & & (price <tbprix [i])) ( / / In the right interval
                                return tableauEstimation [i];
                        }
                        min = tbprix [i];
                }

                assert false : "The price did not match any known intervals";
        }

3.3. Pre / Post conditions and Invariant Functions
:
The preconditions, they are simply the conditions necessary for the proper functioning code included in the method you're about writing. The postconditions are conditions on the state the system as it should be left to the end of the method call. Finally, the functional invariants are all constraints that must meet your class, or rather its object instances to be in compliance with the definition thereof.
Here are examples for these

Precondition
Code:
/**
         * Estimate the price passed as argument.<p>
         * <are color="red">Note this code can not be considered
         * Sturdy, it is stripped of everything that does not directly 
         * Current demonstration: preconditions to using assertions. Use
         * Tables instead of collections is not a good practice
         * But it helps to focus attention on the purpose of the demonstration</are><p>
         * Builds on two tables of same length containing the foundations of price and
         * Associated estimates.
         * <p><i>Verify that the tables are the same length, with at least two values and 
         * price chart is sorted in ascending order</i></p>
         * @ param Price Price in Country
         * @ return A string containing the estimate of the computer
         * @ Throw IllegalArgumentException if the price is negative
         */
        Public String controleDeFlux (int price) throws IllegalArgumentException (

                assert tbprix.length == tbest.length: 
            "The number of intervals does not match the number of estimates";
                assert tableauxPrix.length> 1 : 
            "Unable to define intervals of no value or with a single value";

   
 color = "# a52a2a">for (int i = 0; I <tableau.length -- 1; I + +) (
                        assert tbprix [i] <= tbprix [i +1] : 
                "The values in Table prices are not arranged in the order";
        }

                if (price < 0) { / / The price can not be negative
                        throw IllegalArgumentException ("The price is negative");
                }
                ...
        }
PostCondition
Code:
   /**
         * Adds an object in a collection and verify that the item has been added.<p>
         * <i>This code is again irrelevant out of context:
         * Demonstrate interest and explain the notion of postcondition</i>
         * @ param o the object store.
         */
        Public void add (Object o) (
                int sz = mycollection.size ();
                mycollection.add (o);

                assert mycollection.size () == sz + 1;
        }
Invariant Function
Code:
Public class Car (
        Public void roll () (
                assert 4 == GetRoues.size ():
                        "The car can not run if it did not exactly 4 wheels.";
                ...
        }
...
Reply With Quote
  #3  
Old 25-02-2010
Member
 
Join Date: Feb 2010
Posts: 136
Re: Assertions in Java

4. Development / Deployment:
The development with assertions requires Java 1.4 and further. The compilation has specified that you use the keyword assert to support the argument online Order
Code:
       -source 1.4.
Finally, when starting your application, by default, assertions are disengaged (in order that your user is not obliged to do so), we must specify jvm to use them using the argument command line:

Code:
-ea or -enableassertions.



5. Conclusion:

We are therefore already in the good practices and have tools for making the code intrinsically robust, I remind you quickly these practices:

- Check validity of parameters,

- Document, discuss, and make the code readable so self-documenting,

- Using assertions in particular specify preconditions, postconditions and invariants classes.

There remains only one thing to make sure that code meets the criteria of robustness by putting voluntarily the cases detected as difficult. To do this, you need a way Simple test code. There are unit testing frameworks very effective to do so.
Reply With Quote
  #4  
Old 19-03-2010
Member
 
Join Date: Mar 2010
Posts: 1
Re: Assertions in Java

do we have another software which can substitute java ware?
Reply With Quote
  #5  
Old 19-03-2010
Praetor's Avatar
Member
 
Join Date: Apr 2008
Posts: 1,937
Re: Assertions in Java

Following program can uses simple form of an assertion :
Code:
AssertionDemo.java
Class AssertionDemo
{
	Public static void main(String arg[])
{
		System.out.println( WitdrwMny(1000,500) );
		System.out.println( WitdrwMny(1000,2000) );
	}
	public double WitdrwMny(double blnce , double amnt)
{
		assert blnce >= amnt;
	return blnce - amnt;
	}
}
Reply With Quote
Reply

  TechArena Community > ARENA > Guides & Tutorials


Thread Tools Search this Thread
Search this Thread:

Advanced Search


Similar Threads for: "Assertions in Java"
Thread Thread Starter Forum Replies Last Post
JAVA/Stutter.J.2 is a virus or any kind of java file GaganjyotTechie Networking & Security 6 29-05-2011 10:55 AM
Setting Of Java to The Point At Manual Java winni Software Development 4 10-01-2011 10:05 PM
Java Programming using Adventnet SNMP Java API ROCKING_Suhas Software Development 5 17-07-2010 07:52 AM
How big is an Object in Java? Why Java neglects sizeof? KALINDA Software Development 4 10-11-2009 03:19 AM
Link List Example in Java Sample program in Java trickson Software Development 2 04-08-2009 09:23 PM


All times are GMT +5.5. The time now is 09:49 PM.