26

I been looking at this question, and I thought it would be a good idea of using assert only in debug build.

Is there any thing special that I need to configure in Android Studio in order to allow asserts? I also want to guarantee that they will not be presented in release build.

Community
  • 1
  • 1
Ilya Gazman
  • 31,250
  • 24
  • 137
  • 216
  • Does anybody know any function here? This link is generally useful for [assert in android](http://stackoverflow.com/a/5563637/3824920). However any convenient method in Android Studio would be great. – Denis Lukenich Dec 08 '15 at 08:42

1 Answers1

11

The adb shell setprop debug.assert 1 from your referred question is to be executed on the device you are testing on, so you could whip up a script or even create a custom gradle task for that (gradle docu).

In general I'd recommend to also have your checks in production and handle them in a proper way. A simple solution would be to throw a RuntimeException. With checked Exception you could even handle the recovery from this errorneous states / misuses of your api.

Furthermore, it would make sense to add proper tests that ensure, that your code/APIs only emit "valid" values that can be handled by the rest of your code.

Florian Barth
  • 1,392
  • 12
  • 25
  • Your comment seems to be against assertions, so it is a bad practice in general to use them in Android? I like to use assertions to support me in finding possible bugs fast when i am testing and debugging my applications by using the fail-fast behaviour. But in productive environment i do not want my application to crash easily. The "hope" for my application to somewhow recover is preferred here over a crash. Idependent of that, at points where illegal values are possible (e.g. in case of user inputs), exceptions are clearly the way to go. – Denis Lukenich Dec 10 '15 at 15:14
  • I'm not a great fan of assertions and rather the RuntimeException-Thrower for letting my apps fail fast. I'd second the answer to http://stackoverflow.com/questions/1276308/exception-vs-assertion and leave room for your personal preference. However, with assertions you have to deal with adb for enabling/disabling them. – Florian Barth Dec 15 '15 at 08:08