Welcome!

Java IoT Authors: Yeshim Deniz, Elizabeth White, Liz McMillan, Pat Romanski, Zakia Bouachraoui

Related Topics: Java IoT

Java IoT: Article

Implementing Assertions in Java

Implementing Assertions in Java

Any software system, whether object-oriented or not, relies on the state of the system being "correct" at certain stages of its execution. To take a very simple example, when a numerical division operation is performed, the divisor must be non-zero. If this is not the case, the system may crash in an unpredictable and uncontrolled manner.

One way of indicating such requirements is to state that the system must be in some state either before or after an operation. Such a statement about the state of a software system is called an assertion.

Assertions often form the basis for software specification. In some systems, the assertions are embedded in the software as annotations or formal comments. However, it can be useful to make the assertions executable so that the correctness of the system is checked at runtime.

A simple technique is to make the code do its own self-testing using a method call and a programming languages exception mechanism. The code checks that the statement passed to it is true, thus allowing it to test that the code is behaving as expected. If the statement is false, the method uses an exception to stop processing, thereby enabling debugging.

This article looks at how assertions can be implemented within the Java programming language [1]. In the remainder of this article, we introduce the concept of assertions, how they can be used and how they can be implemented. In particular, we introduce two types of assertions: one which generates a runtime exception if it fails and one which generates a checked exception (which must be handled by the programmer) if it fails. We then provide a brief analysis of the facilities provided by this approach.

Assertions and Their Uses
An assertion is a logical statement about the state of a software system. In formal methods, such as VDM [10], software is specified by making assertions about the pre- and post-conditions of functions and operations. These assertions may be used to formally prove properties of the system, such as consistency. During the development process, the abstract specification is refined into code. The problem with this approach is that the assertions used in the specification are often lost during the refinement process and indeed, it may not be possible to express the assertions in the final implementation language.

Programming languages have been developed which enable assertions to be embedded into the code itself, for example Gypsy [5] or SPARK [3, 2]. Tools available with these language systems enable the assertions to be checked and, in some cases, proved.

Another approach is to introduce assertions into existing programming languages by using formal comments, called annotations, or by pre-processing. The C programming language has been extended with annotations[7] and Ada has been similarly extended into Anna [11]. An annotation pre-processor for C is described in Rosenblum's "A Practical Approach to Programing with Assertions" [13]. In these systems, tool support enables the assertions to be checked against the program code. However, extra-language syntax is required and, in the case of annotations, the assertions are lost when the program is compiled.

It may be better to have assertions as part of the code so that they provide a permanent defensive programming mechanism for detecting faults at runtime [12]. The exception mechanism of a programming language can be used for this [8]. In the following sections we show how this can be done for Java.

Using Assertions in Java
Assertions can be implemented in Java as part of an assertion package (available at http://www.aber.ac.uk/~jjh/Java/assertion). This package can provide assertion classes which take an assertion and throw an exception if the assertion is false. The package could also define its own exceptions, thereby allowing a programmer to catch assertion exceptions. The assertion package we have defined provides two separate assertion classes and two different types of exception:

  • Assertion - The class Assertion allows programmers to use assertions within their code.
  • CheckedAssertion - The class CheckedAssertion allows programmers to use assertions within their code but forces them to explicitly catch a CheckedAssertionException.
  • AssertionException - The AssertionException class extends the RuntimeException class so that programmers do not have to handle the exception raised.
  • CheckedAssertionException - The CheckedAssertionException class extends the Exception class so that programmers are forced to handle the exception raised.

    The difference between the checked and the non-checked assertions for the developer is that they must explicitly handle any exceptions raised by the CheckedAssertion class, whereas they can choose to ignore the fact that an exception may be raised by the Assertion class.

    In Java, a package is an associated group of classes and interfaces [1]. We have defined a new package assertion which holds the four classes listed above. Other classes can then use these four by importing the assertion package. An example of how these classes are used is presented in Listing 1.

    This example creates a simple class Example which uses the Assertion class to handle the result of checking the relationship between a and b. The result of running this application is presented in Listing 2.

    We could have caught the AssertionException within a try{} catch{} block. This construct allows a piece of code to be wrapped up within a try block. The try block indicates the code which is to be monitored for the exceptions listed in the catch expressions. The catch expressions can then be used to indicate what to do when certain classes of exception occur; for example, "resolve the problem" or "generate a warning message", etc. If no catch expressions are included the throws clause must be handled by the method definition. For example:

    try { e.test(1, 2);
    e.test(2, 1);
    }
    catch (AssertionException e) {
    System.out.println("First parameter larger than second");
    }

    This would have allowed us to respond in an appropriate manner. Below we examine the implementation of the Assertion and AssertionException classes and their checked counterparts.

    Exceptions in Java
    In Java, (almost) everything is an object; therefore, exceptions are objects as well. All exceptions must extend the class Throwable or one of its subclasses [4].

    The class Throwable has two subclasses, Error and Exception. Errors are unchecked exceptions. These are exceptions which your methods are not expected to deal with. The compiler therefore does not check that the methods can deal with them. In contrast, most exceptions (but not RuntimeException and its subclasses) below the class Exception are checked exceptions. These exceptions must be dealt with by your methods. The compiler thus checks to see that methods throw only exceptions which they can deal with (or are passed up to other methods to handle). For example, if we wished to raise an ArithmeticException, for a divide by zero error then we would write:

    throw new ArithmeticException("Division By Zero");

    In Java, you are not limited to system-provided exceptions; it is also possible to provide user-defined exceptions. This can be very useful as such an approach can allow the developer to have more control over what happens in particular circumstances. To do so, a developer must subclass the Exception class or one of its subclasses.

    Assertions in Java
    The Assertion class
    The Assertion class (a direct subclass of Object) makes two methods publicly available for handling boolean expressions. These are:

  • assert(boolean bool) - Determines the effect of the boolean result passed to it.
  • assert(boolean bools[]) - Determines the effect of the array of expressions passed to it.

    The second method is really a convenience method which repeatedly calls the first method on each element in the array.

    The implementation of the assert(boolean bool) method is relatively straightforward. The method checks whether the boolean value is false or not. If it is false an exception is raised. The assert(boolean bools []) method simply calls the previous method iteratively (see Listing 3).

    Switching Assertion Checking Off
    In the released version of the system, the assertion checks may waste processing time. they could therefore be replaced by a null version of the method:

    public static void assert (boolean bool) throws AssertionException {
    return true;
    }

    As Java dynamically loads the appropriate .class file at runtime, we could distribute the final version of the system with an Assertion.class file based on the above implementation of assert. We would therefore not even need to recompile the system being released.

    The overhead of the extra method dispatch is relatively small; of course, if it is still significant we could write a utility to find the senders of the assert method and to comment out the assertion statements.

    The AssertionException class
    The AssertionException class is a subclass of the RuntimeException class as illustrated in Figure 1. The definition of the AssertionException class is provided in LIsting 4. Note that it provides two constructors which are used to initialize the string displayed to the user.

    CheckedAssertion and CheckedAssertionException
    These classes are essentially the same as the Assertion and AssertionException classes except that the CheckedAssertion class throws the CheckedAssertionException and the CheckedAssertionException extends the Exception class (as shown in Figure 1). For the developer, the difference between the two types of assertion checking is that any exceptions raised by the CheckedAssertion class must be handled explicitly; they can not simply be propagated out of the program.

    The advantage is that the developer using the assertions can decide how much control to give to the user of a component. If they wish, they can force that user to handle the exception and thereby allow them to take charge of any problems which occur. This can result in code which is more resilient to erroneous situations.

    For completeness, the two classes are presented in Listings 5 and 6.

    Analysis
    Design methods Using Assertions
    Assertions are particularly useful for testing pre-conditions, post-conditions and class invariants. The Syntropy design method makes extensive use of such assertions [6]. It would therefore be possible to use the assertions identified during the design as the basis of the assertions to place in the Java code.

    JavaBeansª
    The use of assertions could be extremely useful when working with JavaBeans (the Java component model). In such situations developers produce reusable components which will be used by developers in many different ways. By using assertions, developers can ensure that the state of the Bean at any time is correct. If the state is not correct then they can take appropriate action. The assertions can therefore be used as guards against inappropriate states, parameters, etc.

    Shortcomings
    The simple approach to inserting assertions into Java code described here cannot provide the following, more sophisticated types of assertions:

  • Assertions that relate output values of methods to their input values: For example, suppose one defined a method which swapped the values of its two parameters.

    void swap (SomeType x, SomeType y) {
    SomeType z;
    z = x;
    x = y;
    y = z;
    }

    One might want to assert, just before the method returns, that the new value of x is equal to the old value of y and the new value of y is equal to the old value of x. This is not possible with our assertion mechanism. Assertion mechanisms for which this is possible have additional syntax which allows the "before and after" values of variables to be distinguished.

  • Assertions which involve quantified expressions: Formal methods, and the annotations of Anna and SPARK, allow expressions to be quantified by "for all", "exists", or "not exists". So, the fact that a natural number N was prime could be asserted by saying that there did not exist numbers P and Q with 1 Conclusions
    Recent commentators have suggested that assertions provide a valuable defensive programming technique. One of the nine ways advocated for making code more reliable is to "use assertions liberally" [9].

    We have demonstrated a simple mechanism for introducing assertions into Java programs. Two classes have been defined: Assertion and CheckedAssertion. The former allows assertions to be used very simply. Any exceptions thrown as a result of the assertions failing may be caught or propagated out of the program. The CheckedAssertion class requires the exceptions to be caught or explicitly listed in a throw clause for the methods involved. This provides greater control and "self documentation" of the assertion mechanism.

    Our assertion mechanism is particularly valuable when Java is used in larger, critical applications, where developers are implementing classes for general use and for Java Beans components.

    References
    1. K. Arnold and J. Gosling, The Java Programming Language, Addison Wesley, ISBN 0-201-63455-4, 1996.
    2. J.G.P. Barnes, High Integrity Ada: The SPARK Approach, Addison-Wesley, ISBN 0-201-17517-7, 1997.
    3. B.A. Carré, J.R. Garnsworthy and D.W.R Marsh, "SPARK: A Safety-Related Ada Subset", in W.J. Taylor (ed.), Ada in Transition, IOS Press, Amsterdam, 1992, pp. 31-45.
    4. P. Chan and R. Lee, The Java Class Libraries: An Annotated Reference, Addison-Wesley, 0-201-69581-2, 1996.
    5. R.M. Cohen, Proving Gypsy Programs, Ph.D. Thesis, The University of Texas at Austin, 1986.
    6. S. Cook and J. Daniels, Designing Object Oriented Systems: Object-oriented modeling with Syntropy, New York: Prentice Hall, 0-13-203860-9, 1994.
    7. D.W. Flater, Y. Yesha and E.K. Park, Extensions to the C Programming Language for Enhanced Fault Detection, Software - Practice and Experience, vol. 23, no. 6, pp. 617-628, June, 1993.
    8. P. Gaution, An Assertion Mechanism Based on Exceptions, in Proc. 4th C++ Tech. Conf., USENIX Association, pp. 245-262, August, 1992.
    9. A. Joch, How Software Doesn't Work, Byte, pp. 49-60, December, 1995.
    10. C.B. Jones, Systematic Software Development using VDM, Prentice Hall, ISBN 0-13-880733-7, 1990.
    11. D.C. Luckham, F.W. von Henke, B. Krieg-Brkner, and O.Owe, Anna - A Language for Annotating Ada Programs, Lecture Notes in Computer Science, vol. 260, Springer-Verlag, 1987.
    12. B. Meyer, Applying Design by Contract, IEEE Computing, vol. 25, pp. 40-51, October, 1992.
    13. D.S. Rosenblum, A Practical Approach to Programming with Assertions, IEEE Transactions on Software Engineering, vol. 21, no. 1, pp. 19-31, 1995.

  • More Stories By John Hunt

    Dr. John Hunt has been working in the object-orientation field since the mid-1980s in both industry and academia. He became interested in Java early in 1995 and has worked with a number of companies (including Sun) with Java. He is particularly interested in developing real world applications using Java and in issues associated with Java performance, integrity and architecture.

    More Stories By Fred Long

    Dr. Fred Long lectures on software engineering and formal methods. He is a visiting scientist at the Software Engineering Institute in Pittsburgh. Recently, he has been researching Java's suitability for the development of critical applications.

    Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    IoT & Smart Cities Stories
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Atmosera delivers modern cloud services that maximize the advantages of cloud-based infrastructures. Offering private, hybrid, and public cloud solutions, Atmosera works closely with customers to engineer, deploy, and operate cloud architectures with advanced services that deliver strategic business outcomes. Atmosera's expertise simplifies the process of cloud transformation and our 20+ years of experience managing complex IT environments provides our customers with the confidence and trust tha...
    Where many organizations get into trouble, however, is that they try to have a broad and deep knowledge in each of these areas. This is a huge blow to an organization's productivity. By automating or outsourcing some of these pieces, such as databases, infrastructure, and networks, your team can instead focus on development, testing, and deployment. Further, organizations that focus their attention on these areas can eventually move to a test-driven development structure that condenses several l...
    The graph represents a network of 1,329 Twitter users whose recent tweets contained "#DevOps", or who were replied to or mentioned in those tweets, taken from a data set limited to a maximum of 18,000 tweets. The network was obtained from Twitter on Thursday, 10 January 2019 at 23:50 UTC. The tweets in the network were tweeted over the 7-hour, 6-minute period from Thursday, 10 January 2019 at 16:29 UTC to Thursday, 10 January 2019 at 23:36 UTC. Additional tweets that were mentioned in this...
    Over the course of two days, in addition to insightful conversations and presentations delving into the industry's current pressing challenges, there was considerable buzz about digital transformation and how it is enabling global enterprises to accelerate business growth. Blockchain has been a term that people hear but don't quite understand. The most common myths about blockchain include the assumption that it is private, or that there is only one blockchain, and the idea that blockchain is...
    Never mind that we might not know what the future holds for cryptocurrencies and how much values will fluctuate or even how the process of mining a coin could cost as much as the value of the coin itself - cryptocurrency mining is a hot industry and shows no signs of slowing down. However, energy consumption to mine cryptocurrency is one of the biggest issues facing this industry. Burning huge amounts of electricity isn't incidental to cryptocurrency, it's basically embedded in the core of "mini...
    In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
    The term "digital transformation" (DX) is being used by everyone for just about any company initiative that involves technology, the web, ecommerce, software, or even customer experience. While the term has certainly turned into a buzzword with a lot of hype, the transition to a more connected, digital world is real and comes with real challenges. In his opening keynote, Four Essentials To Become DX Hero Status Now, Jonathan Hoppe, Co-Founder and CTO of Total Uptime Technologies, shared that ...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.