aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Assertions Q Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Assertions Q" Watch "Assertions Q" New topic
Author

Assertions Q

Kedar Dravid
Ranch Hand

Joined: May 28, 2004
Posts: 333
Which of the following code fragments are appropriate uses of assertions?

a.)
public void openSocket(int port)
{
assert port > 1000;
...
}
b.)
public void openSocket(int port)
{
Socket s = //open socket;
...
assert s != null;
}
c.)
public boolean doSomething()
{
...
}
public void someMethod()
{
assert doSomething();
}
d.)
private void processArray(Object[] arr)
{
assert arr.length == 10;
...
}


Select 2 correct options
a a

b b

c c

d d

Given answers: b, d.
Finw with me. But, why not c?
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17260
    
    6

It's not c because c calls a method in the assert. That method might change some state, or be needed to do some part of the methods algorithm. And if assertions are turned off, then your algorithm will not work in production.

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Animesh Shrivastava
Ranch Hand

Joined: Jul 19, 2004
Posts: 298
Whats the problem with option a?
Kedar Dravid
Ranch Hand

Joined: May 28, 2004
Posts: 333
Assertions should not be used for checking arguments of public methods.
That's why option a) doesn't qualify.
Animesh Shrivastava
Ranch Hand

Joined: Jul 19, 2004
Posts: 298
The argument of the method is having only the method scope and also in the option b, the object s of Socket is having method scope. Then why not option b?
Please explain me, i am not aware of this.

Thanks
Kedar Dravid
Ranch Hand

Joined: May 28, 2004
Posts: 333
Assertions should not be used to validate information supplied by a client. A typical example is argument checking in public methods. Argument checking is part of such a method's contract, which could be violated if assertions were disabled.
In choice a, actual value for port is provided when method is invoked. It could be information supplied by a client.
[ March 12, 2005: Message edited by: Kedar Dravid ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Assertions Q