4 ms·
I wouldn't say they're always code smells. Like they say in the video, a call to the 'myString.IsNullOrEmpty()' extension method is a null check, but there's no
by taco_emoji 9y ago
I wouldn't say they're always code smells. Like they say in the video, a call to the 'myString.IsNullOrEmpty()' extension method is a null check, but there's no way to prove that to the compiler.
- dep_b 9y agoI think that's more of a compiler problem then. Also what's missing is the unwrap syntax to easily transform between nullable and non-null references. What you really want is to operate on a non-null version of that reference if it's proven to be non-null, this is really the Achilles heel of this particular implementation. You're still checking for null all over the place, it's just better checked. // Unholy mix of Swift and C# syntax ahead! if var unwrappedString = wrappedString && unwrappedString != "" { unwrappedString.Length(); } Where the `if var unwrappedString = wrappedString` part would unwrap the var and return a `bool` at the same time which is `true` if it wasn't `nil`. Swift's nil-checking / unwrapping syntax is really short and with some clever usage of `map` or `flatMap` you can still have one-liners albeit a bit more verbose - but much more secure. Example of using map: let myTitle = myObject?.title.map { "Item \($0)" } ?? "No title" This code can't even theoretically crash anymore and doesn't force unwrapping with `!` as a traditional approach would do: let myTitle = myObject?.title != nil ? "Item \(myObject!.title!)" : "No title"
- int_19h 9y agoYou can totally do this in C#, since it has lambdas, and you can use the extension method to add "map" to nullable references of arbitrary types. It also has ??. The problem is that lambdas aren't free. For something as simple as a null check, the overhead of a lambda is excessive. Zero-cost lambdas are possible, but require a new type of lambda that cannot escape the enclosing scope, all reflected in the type system.