9. What is design by contract? Explain the assertion construct?


Design by contract specifies the obligations of a calling-method and called-method to each other. Design by contract is a valuable technique, which should be used to build well-defined interfaces. The strength of this programming methodology is that it gets the programmer to think clearly about what a function does, what pre and post conditions it must adhere to and also it provides documentation for the caller. Java uses the assert statement to implement pre- and post-conditions. Java’s exceptions handling also support design by contract especially checked exceptions. In design by contract in addition to specifying programming code to carrying out intended operations of a method the programmer also specifies:

Preconditions – This is the part of the contract the calling-method must agree to. Preconditions specify the conditions that must be true before a called method can execute. Preconditions involve the system state and the arguments passed into the method at the time of its invocation. If a precondition fails then there is a bug in the calling-method or calling software component.

On public methods

On non-public methods

Preconditions on public methods are enforced by explicit checks

that throw particular, specified exceptions. You should not use

assertion to check the parameters of the public methods but

can use for the non-public methods. Assert is inappropriate

because the method guarantees that it will always enforce the

argument checks. It must check its arguments whether or not

assertions are enabled. Further, assert construct does not throw

an exception of a specified type. It can throw only an

AssertionError.


public void setRate(int rate) {

if(rate <= 0 || rate > MAX_RATE){

throw new IllegalArgumentException(“Invalid rate : ” + rate);

}

setCalculatedRate(rate);

}


You can use assertion to check the parameters of the

non-public methods.


private void setCalculatedRate(int rate) {

assert (rate > 0 && rate <>

//calculate the rate and set it.

}


Assertions can be disabled, so programs must not

assume that assert construct will be always executed:


//Wrong: if assertion is disabled, CarpenterJob never

//Get removed

assert jobsAd.remove(PilotJob);


//Correct:

boolean pilotJobRemoved = jobsAd.remove(PilotJob);

assert pilotJobRemoved;



  • Postconditions – This is the part of the contract the called-method agrees to. What must be true after a method completes successfully. Postconditions can be used with assertions in both public and non-public methods. The postconditions involve the old system state, the new system state, the method arguments and the method’s return value. If a postcondition fails then there is a bug in the called-method or called software component.public double calcRate(int rate) {
if(rate <= 0 || rate > MAX_RATE){
throw new IllegalArgumentException(“Invalid rate !!! ”);
}

//logic to calculate the rate and set it goes here
assert this.evaluate(result) < 0 : this; //this �� message sent to AssertionError on failure
return result;
}

  • Class invariants - what must be true about each instance of a class? A class invariant as an internal invariant that can specify the relationships among multiple attributes, and should be true before and after any method completes. If an invariant fails then there could be a bug in either calling-method or called-method. There is no particular mechanism for checking invariants but it is convenient to combine all the expressions required for checking invariants into a single internal method that can be called by assertions. For example if you have a class which deals with negative integers then you define the isNegative() convenient internal method:
class NegativeInteger {
Integer value = new Integer (-1); //invariant

//constructor
public NegativeInteger(Integer int) {
//constructor logic goes here
assert isNegative();
}

//rest of the public and non-public methods goes here. public methods should call assert isNegative(); prior to its return

//convenient internal method for checking invariants. Returns true if the integer value is negative
private boolean isNegative(){
return value.intValue() < 0 ;
}
}

The isNegative() method should be true before and after any method completes, each public method and constructor should contain the following assert statement immediately prior to its return.

assert isNegative();

Explain the assertion construct? The assertion statements have two forms as shown below:

assert Expression1;

assert Expression1 : Expression2;
Where:
  • Expression1 - is a boolean expression. If the Expression1 evaluates to false, it throws an AssertionError without any detailed message.
  • Expression2 - if the Expression1 evaluates to false throws an AssertionError with using the value of the Expression2 as the errors’ detailed message.
Note: If you are using assertions (available from JDK1.4 onwards), you should supply the JVM argument to enable it by package name or class name.

Java -ea[:packagename...|:classname] or Java -enableassertions[:packagename...|:classname]
Java –ea:Account


14 comments:

  1. I really appreciate the kind of topics you post here. Thanks for sharing us a great information that is actually helpful. Good day! Please search instagram story viewer to discover nice photos and videos on instagram.

    ReplyDelete
  2. There is no real guaranteed way to be successful in cricket betting tips and strategy. However, you need to do all the research that you can, do your homework on all the teams, their stats, the players form, the conditions of the matches etc. This is risky, but like most of the risky strategies, if you get it right, you can make a pretty decent win on it.
    https://techpower.hatenablog.com/entry/2021/01/18/190617?

    ReplyDelete
  3. This is risky, but like most of the risky strategies, if you get it right, you can make a pretty decent win on it.To help you do all the research about cricket betting tips and strategies cricket betting india will help and guide you with it, so the rate of success is increased, because not only you need your luck by your side but also enhanced skills and knowledge of all the process.
    https://my-blogging-channel-15.webself.net/blog/2021/03/09/online-cricket-betting-sites-in-india

    ReplyDelete
  4. If you want to learn how to bet on cricket? Cricket betting india.org is a website dedicated to providing you with the most easy details on cricket betting tips, cricket betting terminology, and online betting India. We compile online cricket betting guides in India.
    https://gervaisjervis9.wixsite.com/tooltech/post/how-should-one-bet-on-cricket-analysis-of-cricket-betting

    ReplyDelete
  5. What's up? I came across your website while searching for a related topic on Google. It seems to be well. I've added it to my Google bookmarks so I can get back to it later.

    https://rabbitroom.com/members/virat14/profile/

    ReplyDelete
  6. One of the main factors to consider when choosing Betfair Casino Login is the trustworthiness of the online betting sites. This can be researched using the past reviews on that online betting sites. https://gab.com/fatwallet/posts/106295394181048631

    ReplyDelete
  7. It's one of the most impressive blogs I've ever seen. In my perspective, everything of the stuff on this site is highly creative and nicely written. As a result, I've wished to return. https://eternalpirates.com/forum/member.php?action=profile&uid=5402

    ReplyDelete
  8. Bet 365 Withdraw Charges allow the people doing betting online to bet on the teams and players with only a few clicks. With bet 365 withdraw charges anyone can do betting online in India. We review all the Online Casinos and betting sites in India to provide our visitors a clear overview about everything. https://ello.co/fasttrackgroup/post/rfljuw2puq5iiltxmxvsya

    ReplyDelete
  9. Choosing the what is abc code in paytm is of key significance when it comes to online cricket betting. A large sum of online cricket betting sites exists in India.
    https://www.h2fanatic.com/forum/member.php?u=62448

    ReplyDelete
  10. It's one of the most impressive blogs I've ever come across. Everything on this site, in my opinion, is quite unique and well-written. As a result, I've wanted to go back. https://emailfinder.medium.com/email-marketing-vs-social-media-which-is-best-for-your-business-6471d6167e93

    ReplyDelete
  11. Utilizing the latest accounting techniques to save time and money Our accountant Vancouver will assist you with payroll, taxation, and bookkeeping. Our focus is on working with large to small businesses to meet their tax objectives.
    https://www.qantumthemes.com/helpdesk/forums/users/kehalcpa/

    ReplyDelete
  12. Our collection of Joggers for girls is made with the comfort of your child in mind. The majority of our joggers have been constructed from organic cotton that is soft along with our bottoms for tracksuits that go nicely when paired with printed or plain Tee-shirts. Choose from a range of everyday colors like navy, black gray, and black. You can also opt for fun stripes and prints on the leg to complement your individual fashion sense. Check out the collection below or scroll down for toddler outfits to dress easily.
    https://www.xaphyr.com/Anthrilo

    ReplyDelete
  13. Speak to SWG Mortgages specialist advisors to find out more about lenders who offer mortgages for homes. SWG Mortgages advisors have plenty of knowledge of negotiating with different lenders, and can assist you in utilizing particular lenders.
    https://www.redbubble.com/people/swgmortgages

    ReplyDelete