This isn’t a Julia related program, but rather a programming problem in general.
Suppose you’re designing the validation system for a school that issues ID cards to it’s students. One rule is that you don’t want students who have graduated, but still carry a ID card, to enter the school and start using rooms and facilities that are meant for currently enrolled students (for example, you may need a valid ID to login to a computer).
You might write your function like this:
struct Student
ID::String
name::String
end
function validate_students(student_db::Vector{Student},student::Student)
if !(student in student_db)
throw(DomainError(student.ID,"Student ID is invalid."))
end
# additional validation
end
Keep in mind this is a very simplified example to illustrate my problem. I’m fully aware that a database of students won’t be a Vector{Student}
and Student
would obviously have an inner constructor and validation.
I’ve been reading Exception Handling:When and Why and I’ve been told that Exceptions should only be used in exceptional cases. How do I know if my case is exceptional?.
Is my case an exceptional one? Before using the rooms and facilities we expect the student to be currently enrolled.
The use of if
statements presents a problem, it doesn’t stop the workflow of the function.
function validate_students(student_db::Vector{Student},student::Student)
if !(student in student_db)
println(student.ID,"Student ID is invalid.")
end
# additional validation -- but we shouldn't be here if the validation above
returns false.
end
Consider if additional validation has to be done, if we used just if/else
statements, we continue on, even after it’s been determined that student
should be considered invalid after the first check.