javaassertpublic-method

Why can't we use assertion for public methods?


Why can't we use assertion for public methods?

I have read somewhere

"An assert is inappropriate in public methods because the method guarantees that it will always enforce the argument checks. A public method must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type. It can throw only an AssertionError".

So, wont it applicable for private method too?
I didn't understand the above statement clearly


Solution

  • The important distinction is whether you believe an incorrect value is the result of

    a) A programming bug which should be fixed in code.

    b) An input error which cannot be prevented in code and instead need to be handled at runtime.

    For the first case, you should use an assert, as the program code will need to be fixed. If its the later case, you should use an appropriate Runtime or check exception.


    IMHO assertions are for detecting programming errors and not user/external inputs. Perhaps the author is confusing public methods as an external input when you will have public method which are not called by an external input.

    I would use assertions to check arguments to detect programming errors. IMHO this is often the best use for them. Private method by comparison should only be called by code in the same class and you should expect them to be well unit tests and have limited possible access/usages.

    I find that you are far more likely to have programming error via public interfaces because different people make different assumptions (assertions are a good way to document and check assumptions) Internal checks are not as useful as you would expect the same programmer to have access to the internal code if not having written the whole internal code base.