Jump to content

something confusing about assertion in Java...


albertlee

Recommended Posts

Just a simple question about assertion...

 

I heard a statement that assertion is most appropriately used to precondition that checks for a non-public method... such as

 

[b]protected/private/[i]default[/i][/b] void addDevil(String devilName)
{assert isValidDevilName(devilName);}

 

but isn't appropriate for public method.

 

 

Why?????????

 

please help

 

thanks

Link to comment
Share on other sites

http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html#usage-conditions

 

It explains here why. It sounds like it's because with a public method, it will go on to be used by another class or even another coder and will be used alot more outside of the general scope of this class. Asserts are generally not run at runtime (afaik) and you have to specify during runtime that you want them enabled. This is great for debugging but when you have finished, you will still need your public methods to check the validity of parameters passed in, even outside of debugging, because another class or even another coder might pass in a value that is unacceptable, whereas the private and protected methods are only being passed parameters from within the same class or at least a very limited scope, and so you can control the parameters that they are passed and the assertions that their arguments are valid should hold true, as long as you check to make sure that anything that might change this from outside (ie when arguments/parameters are passed to a public method) are valid.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.