Results 1 to 5 of 5

Thread: Assertions in Java

  1. #1
    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.

  2. #2
    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.";
                    ...
            }
    ...

  3. #3
    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.

  4. #4
    Join Date
    Mar 2010
    Posts
    1

    Re: Assertions in Java

    do we have another software which can substitute java ware?

  5. #5
    Join Date
    Apr 2008
    Posts
    1,948

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

Similar Threads

  1. Replies: 4
    Last Post: 04-09-2013, 11:04 PM
  2. Java Programming using Adventnet SNMP Java API
    By ROCKING_Suhas in forum Software Development
    Replies: 5
    Last Post: 17-07-2010, 06:52 AM
  3. Comparison between core java and advanced java
    By Prashobh Mallu in forum Software Development
    Replies: 5
    Last Post: 19-01-2010, 10:57 AM
  4. Link List Example in Java Sample program in Java
    By trickson in forum Software Development
    Replies: 2
    Last Post: 04-08-2009, 08:23 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,711,612,699.10657 seconds with 17 queries