Assertions are disabled when the app is built for production, so the users will not see their app crashing.
One can use assertion for verifying a condition is fulfilled in the case when the current implementation excepts it to be always fulfilled.
Assume the program is iterating the elements of an array. One would expect the the index of the current element is always positive and less than the number of elements in the array.
Sometimes the data is depending on external factors (for example an external library) and there is a chance that it might be incorrect.
Let's consider an app that records the information about a user in the following class (we kept only the functionality needed for our example):
class User {
var age: Int = 0
func setAge(age:Int) {
self.age = age
}
}
Our app is asking the user to input their date of birth, that needs to be before today's date, and then computes the age. In the current scenario, the age will always be positive.
What if the functionality changes in the future and the age is read from a database? From various reasons, one being corrupt data, the age can be negative so the functionality of our program will not work properly.
We want to catch that issue right when it happens.
For this we can add an assert in the following way:
class User {
var age: Int = 0
func setAge(age:Int) {
assert(age >= 0, "Age is not positive. Current value is \(age)")
self.age = age
}
}
Here is some test code:
let user = User()
user.setAge(10)
user.setAge(-5)
The second time the age is set, our program will crash preventing other errors to be raised later.
Of course, one should never use asserts for all the cases. For example, if in our case the age is input by the user, he can introduce a negative one or maybe a non numeric value. In this case, the program should validate input data is correct and display a nice message.
Asserts are only for cases when we are positive that a certain condition is fulfilled all the time.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.