Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Expo on Google News


2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
SYS-CON.TV
Top Links You Must Click On


Programming Correctness, Assertions and Exception Handling
Programming Correctness, Assertions and Exception Handling

Program correctness may be viewed as proof that the computation, given correct input, terminated with correct output. The person who invokes the computation has the responsibility of providing the correct input, which is a precondition. If the computation is successful, we say that the computation has satisfied the postcondition. The Eiffel programming language (www.eiffel.com) for example, encourages programmers to provide a fully formal proof of correctness by writing assertions that may appear in the following roles

  • Precondition - a condition an operation's caller agrees to satisfy. In Eiffel the keyword require introduces a precondition.
  • Postcondition-- a condition that the method itself promises to achieve. In Eiffel the keyword ensure introduces a postcondition.
  • Invariant-- a condition that a class must satisfy at all times. The invariant keyword introduces an invariant in Eiffel.

    These three roles collectively support what is called the contract model of programming, a model that's well supported by the Eiffel programming language. Java, on the other hand, doesn't have built-in support for this model. Actually, Java doesn't even have built-in support for assertions. However, Java has a far superior feature to assertions - exception handling (see the Java tutorial on JavaSoft, "Handling Errors with Exceptions," for details).

    C-Style Assertions
    An assertion is a Boolean expression that, if evaluated as false, indicates a bug in the code. This mechanism provides a way to detect when a program starts falling into an inconsistent state. Assertions are also excellent for documenting assumptions and invariants about a class. Using assertions helps programmers write better code in terms of correctness, readability and maintainability. Thus they improve the odds that the behavior of a class matches the expectations of its clients.

    In C/C++ you can use assertions through assert. In ANSI C, assert has the following definition:

    void assert(int expression)

    The assertion will be executed only when the macro NDEBUG is undefined. The program will be aborted if the expression evaluates to false (0); if the expression evaluates to true (non-0), assert has no effect. For performance reasons, however, you should write assertions into software in a form that can be optionally compiled. Thus assertions should be executed with the code only when you're in the debugging stage of software development -- that's where assertions will really help in flushing out errors. Note: Assertions represent a uniform methodology that replaces the use of ad hoc conditional tests.

    Implementing Assertions in Java
    You can implement assertions in Java quite nicely. First, create a new exceptions class for your assertions class, as shown in Listing 1.

    Listing 1 extends RuntimeException, a direct subclass of Exception. Basically, there are two kinds of exceptions: checked and unchecked. The possible exceptions in Java are organized in a hierarchy of classes rooted at class Throwable, which is a direct subclass of Object. The classes Exception and Error are direct subclasses of Throwable. Instances (and subclasses) of Error and RuntimeException are called unchecked exception(s) (classes).

    In checked exceptions the Java language checks at compile time whether a Java program contains handlers for exceptions. However, unchecked exceptions (as in RuntimeExceptions) are excluded from this checking. Thus Java simplifies the programmer's task by not requiring you to declare such exceptions, which could be an irritating process.

    The code in Listing 2 implements an assert method, which takes a Boolean expression as an argument and checks whether it's true or false.

    If it's false, your new exception, AssertionException (declared in Listing 1), will be thrown; otherwise nothing happens. Note that in the assert method you're also checking whether the value of NDEBUG (which is Boolean) is on or off. If it's on (set to true), then the assertion is to be executed; otherwise it should have no effect. Also note that clients who use the Assert class should be able to change the value of NDEBUG from their own programs.

    Listing 3 provides a simple demonstration of how to use the Assert class. If you don't want assertions to be executed as part of the code, you could declare the line:

    Assert.NDEBUG = false

    which is really an easy way of turning off the execution of assertions. If you run the program in Listing 3, you'll see the following output:

    % java TestAssertion
    Please input a number: -1
    AssertionException
    at Assert.assert(Assert.java:5)
    at TestAssertion.main
    (TestAssertion.java:15)

    A word of caution: never use the Assert class expression that involves side effects. Writing

    Assert.assert(++i > 0)

    for example, isn't a good idea, because the variable i won't be incremented if Assert.NDEBUG is set to false!

    The Downside of Assertions
    The use of assertions replaces the ad hoc use of conditional tests with a uniform methodology. This methodology doesn't allow for a repair strategy to continue program execution, however. This means that when an exception is detected, the program aborts with no recovery mechanism. This is certainly preferable to undefined behavior when something goes wrong, but it's unacceptable for a wide variety of applications. For example, a program that acquires resources (e.g., a lock on a database) shouldn't be allowed to abort without releasing those resources. A superior feature to assertions is built into Java - exception handling. It's superior in the sense that it allows you, using try/catch/finally, to throw an exception object instead of aborting.

    Conclusion
    When writing programs, you'll find it's a good idea to put checks at strategic places for violations of basic assumptions. These checks help in debugging code. The Assert class implemented in this article provides a convenient way for programmers to abort Java programs while printing a message stating where in the program the error was detected. Remember, these messages are for us - the programmersÊ- not for users. Exception handling in Java is a superior methodology for handling errors when something goes wrong.

    About Qusay H. Mahmoud
    Qusay works for Etisalat College of Engineering, UAE. Previously he worked for Newbridge Networks and Carleton University, both in Canada. Qusay is the author of an upcoming book on distributedprogramming with Java.

  • In order to post a comment you need to be registered and logged in.

    Register | Sign-in

    Reader Feedback: Page 1 of 1

    Enterprise Open Source Magazine Latest Stories . . .
    Apache Deltacloud, the Red Hat-contributed ReSTful API that abstracts differences between clouds so services on any cloud can be managed – provided of course there’s a driver – has graduated from the Apache Foundation’s incubator and is now a full-fledged Top-Level Project (TLP). The...
    With Cloud Expo 2012 New York (10th Cloud Expo) just four months away, what better time to start introducing you in greater detail to the distinguished individuals in our incredible Speaker Faculty for the technical and strategy sessions at the conference... We have technical and st...
    AMD said late Tuesday that its chief sales officer Emilio Ghilardi had left the company and that CEO and president Rory Read is going to do his job while a replacement is sought. AMD didn’t say why Ghilardi left but it’s assumed Read wants his own people. Read is relatively new to th...
    During the lifespan of M3 (Monitis Monitor Manager) there has always been something lacking – timers. M3 execution procedure was outlined in this previous article. The execution mentioned in the latter was a one-time-execution, whereas server monitoring requires periodic invocati...
    Red Hat is putting its bought-in Gluster scale-out NAS storage technology, acquired in October, on the Amazon cloud. It’s styled Red Hat Virtual Storage Appliance for Amazon Web Services and other clouds are supposed to follow in short order.
    A new episode of the screencast series is now available at the OpenNebula YouTube Channel. This screencast demonstrates the new easily-customizable self-service portal for cloud consumers. Its aim is to offer a simplified access to shared infrastructure for non-IT end users. The scree...
    Subscribe to the World's Most Powerful Newsletters
    Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
    Click to Add our RSS Feeds to the Service of Your Choice:
    Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
    myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
    Publish Your Article! Please send it to editorial(at)sys-con.com!

    Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


    SYS-CON Featured Whitepapers
    ADS BY GOOGLE