4 ms·
>Map and pattern matching are not silent. I'm writing a complicated algorithm and am at a point where I know for certain that a given value must be non-nil. S
by layoutIfNeeded 8y ago
>Map and pattern matching are not silent.
I'm writing a complicated algorithm and am at a point where I know for certain that a given value must be non-nil. Sometimes it can be nil, but at this point it's provably non-nil (E.g. at the end of Dijkstra's algorithm every entry in the distance vector must be non-nil - assuming the graph is connected). The type system can't prove this, but I know that it's non-nil at this point.
So, when I access it, I want the program to fail loud and clear, because it means that I've messed up somewhere. Handling it via map or pattern matching makes no sense here. What would you write in the nil case of the pattern matching anyway? return -1? That's absurd. abort()? That's exactly what get() does.
- the_af 8y agoThere are unsafe escape hatches for the rare cases where you do need them, but they aren't recommended. It's not the idiomatic usage, which is why the original post in this thread saying "it'll blow up when I do Optional.get" is mistaken. If it's provably non-nil, use get. But you must provide the proof, and your first reaction must always be "I'm not sure I can assume this". > What would you write in the nil case of the pattern matching anyway? return -1? That's absurd. Yes, it's absurd. You don't return this type of sentinel values in statically typed languages with optional types. If you don't need to discriminate the error, sometimes returning Nothing will suffice. If you need the error, you can use an Either type (where traditionally Left is used for the error). Again, this isn't something I made up. It's how Optionals are used. I suggest you read the link I posted above.
- munk-a 8y agoIf you have something that might be nil earlier, then some stuff happens and you know it definitely isn't nil anymore then why is it still in an option, isn't the logical path split that diverted those "might be nil" cases where a case handling the nil would peel off leaving you not with a maybe but with a real value? I think that sort of pattern is a bad code smell, you are propagating doubt where there is none leading to misleading code that has assumptions that differ from what's on the page - obviously I don't have a real example in front of me so there may be good allowances for understanding but I don't find your core premise to be sound and I feel like any counter example would have a lot of work to do to appear convincing.