Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Assertions in android is avoided

Tags:

java

android

i am doing one Android app.My client is asking me to include assertions in the android code.I have googled across and found that Commonsware says that assertions should be avoided in android code.But i need a strong reason why using assertions is avoided? Please let me know if i should use assertions or not.And if so what are the rules or suggestions using assertions in android.

like image 799
anshul Avatar asked May 05 '26 12:05

anshul


1 Answers

But i need a strong reason why using assertions is avoided?

An assertion is intentionally introducing an unhandled, uncatchable error (AssertionError, specifically).

Assertions do no work in Android by default. You have to specifically enable them. This means that whatever logic you are trying to validate via assertions will not be employed on production devices.

Hence, I agree with this assessment:

Step zero: Refactor comments into assertions

Step one: Refactor assertions out of the code into unit tests

Step three: Escalate the remaining assertions into program exceptions

So you are certainly welcome to validate inputs, confirm outputs, etc. Just do not use assert. Instead, handle the condition in some other fashion. If nothing else, throw a RuntimeException like an IllegalArgumentException, so that your top-level unhandled-exception logic can get control.

A trivial search of the Internet will turn up many articles regarding the choice of assertions versus exceptions, such as:

  • https://softwareengineering.stackexchange.com/questions/137158/is-it-better-to-use-assert-or-illegalargumentexception-for-required-method-param

  • https://stackoverflow.com/a/1276318/866172

like image 103
CommonsWare Avatar answered May 07 '26 02:05

CommonsWare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!