• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assertions Q

 
Kedar Dravid
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Animesh Shrivastava
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whats the problem with option a?
 
Kedar Dravid
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assertions should not be used for checking arguments of public methods.
That's why option a) doesn't qualify.
 
Animesh Shrivastava
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic