3 ms·
I upvoted you because I think it's unfair that you are being downvoted while contributing to the discussion, that said you are completely wrong. Without Optiona
by K0nserv 7y ago
I upvoted you because I think it's unfair that you are being downvoted while contributing to the discussion, that said you are completely wrong. Without Optional/Maybe nulls leak everywhere except you have no idea where they are. This leads programmers to engage in defensive programming for all references since there is nothing to help them understand what they should expect to be null in some cases. Optional/Maybe encourages good data modelling by making values that might be missing very clear. It encourages a style of programming that eliminates these issue via better modelling or by rejecting bad data earlier.
For example consider a network response that in a JS app might be passed around as an opaque object. In a language like Swift this is infeasible, you have to transition from the network serialized version to concrete models at the network layer. If you encounter mismatches in the expectation of what is optional you have to handle it here at the edge of the program. This enables massively safer code and makes reasoning about your program much simpler if anything.
As a concerete example say an API response tells you if a user is verified(for some domain specific definition of "verified"), additionally you want to know when they were verified maybe to give them a hint when they need to do it again. You coudl model this as:
{
"verified": false,
"verified_at": null
}
before they have verified and
{
"verified": true,
"verified_at": "2020-02-24T15:31:12Z"
}
after they have verified.
In Swift this would then be modelled as
struct Users {
let verified: Bool
let verifiedAt: Date?
}
However this introduces an Optional which complicates code that needs to deal with users who are verified or not. Instead you could model the same thing and avoid this issue as:
{
"verification_status": {
"status": "unverified"
}
}
for the unverified case and
{
"verification_status": {
"status": "verified",
"at": "2020-02-24T15:31:12Z"
}
}
for the verified case. In Swift this can be nicely modelled without any Optionals using an enum
enum VerificationStatus {
case unverified
case verified(Date)
}
struct User {
let verificationStatus: VerificationStatus
}
Better optional value visibility leads to better data modelling.