3 ms·
One thing about the null checking stuff that I started thinking about... wouldn't it be more cleaner and less error prone if accessing subproperties of null cla
by mhomde 12y ago
One thing about the null checking stuff that I started thinking about... wouldn't it be more cleaner and less error prone if accessing subproperties of null classes always returned null instead of an exception? ie:
var someVar = class1.class2.SomeProp;
would return null, even if class1 was null. I have a hard time coming up with cases where you actually would want to force an exception. I realize however they reason for the new operator since they might not want to change how existing code works...
- ajanuary 12y agoObjective-C does this. I've not used Objective-C enough in the wild to say how often it causes issues.
- Lukassus 12y agoI think this has to do with types. In what you propose the returned type for primitive types (int, ...) would always be `Nullable<T>` and you would have to cast them to get the type `T`. In many cases you can guarantee that the sub-property is not null and you can safely access the value. I think the proposed operator `.?` is the perfect solution and gives you the flexibility to decide what you can guarantee and how you want to access the sub-property.
- mhomde 12y agoI don't think you should involve nullables ,the compiler would simply rewrite to check if link in the chain is null and then assign to null. But value types are a good point, either it could then set it to default(T) or not set it at all, but it kinda has to be default(T) because null makes most sense for reference types. Might give some unexpected behavior if it variables are set to 0 because of a null reference
- joesb 12y agoIf your code is wrong you want to fail as soon as possible. # authenticator == null if (authenticator.getSessionError(session) == null) { # Assumed session is okay, actually the bug is null authenticator }
- mhomde 12y agohmm, yeah, that's a really good point. I guess this could sorta be resolved if you had non-nullable reference types. You get the feeling though many of these problems comes down to null's largely being a language defect in itself which should have been adressed differently