Witscale Test Center

5.6 Assertions


5.6 Assertions

Many times while implementing some functionality, you need to make certain assumptions about the input data, which you think will be true when you run your code. Say for instance, you are writing a generateSchedule(int month) method for creating a monthly schedule. You assume that the month argument is between 1 and 12. If you are not sure about your assumption, then you can put the if-else conditions to test whether the month that is being passed as an argument really falls between 1 and 12. You may also put a comment in your method stating something like “this method assumes the month between 1 to 12”. 

Commenting your assumptions or verifying them with if-else conditions is useful for debugging your code. However, the code you need to write is not a very elegant one. Moreover, when you deploy your code, you make sure that it is bug free. Therefore, you no longer need these checks and you need to manually remove them.  Java introduced a new mechanism called assertions, to spare you from this hassle. Assertions let you write a clean and readable code to document as well as assert your assumptions during the development time. You can later disable them when you deploy your code.