Instead of `Enumerable.Empty()` or `Array.Empty()` since C# 12 we can also use `[]` to denote an empty collection which will be compiled down to the same.
@garcipat11 ай бұрын
There was also something even berrer performing he showed in a video but dont remember that it was. Domething that is only compiled once by the compiler and done.
@jamesreynolds316711 ай бұрын
Just using [] leads to the same issue described in this video. We don't know the type when just reading the code. We then have to look at the return type of the method to know what we're returning. I think Array.Empty and Enumerable.Empty is best since it describes its type.
@maschyt11 ай бұрын
@@jamesreynolds3167 that depends if the specific type is relevant or if you only care to know that a collection is returned. In the latter case just returning [] may be fine to denote that an empty collection is returned. As mentioned in the video the issue with `default` is not so much that you can’t immediately see the exact type it, but mostly that you can’t immediately see the value that gets returned. Because for this you need to know if the type is a reference type, nullable value or type or non-nullable value type, and some more. This is less of an issue with [] where you can immediately see that the return value is an empty collection.
@jdsaravaiya646811 ай бұрын
@@garcipatits Enumerable.Empty()
@zagoskintoto11 ай бұрын
I'm glad you showed returning an empty enumerable. Returning nullable IEnumerables triggers my ocd
@vivekkaushik950811 ай бұрын
You need some fentanyl to chill out dude. 😂😂
@djp_video11 ай бұрын
But there is a difference between an empty result and an unavailable result. That's why we return nulls -- to indicate that the requested data isn't available -- not just that there aren't any results. I'd much rather know that "the data you want isn't available now" instead of "there is no data that matches your request." The most common alternative, throwing an exception, is a bad idea. It kills performance and eats up a lot of memory generating the exception object, error message, and a stack trace that is not likely to be used.
@zagoskintoto11 ай бұрын
@@billyhagood6014 I would check for null if the signature said it could be null, I don't get where you are coming from. Just because I don't like implementing returning a null collection, because I believe it adds 0 valuable information, doesn't mean I don't work around how others implement their stuff.
@Crozz2211 ай бұрын
Whenever I see Task I think that the method should really have been a IAsyncEnumerable
@orterves11 ай бұрын
A domain model that uses null as a special value for an enumerable compared to using an empty should be revised. Null has a very niche purpose, every other use was a billion dollar mistake that is better served by types like Result and Option
@AlexBroitman11 ай бұрын
Agree. Returning default when you know the type is bad. In addition I don't like to check Any() as in the example. Any() causes multiple enumeration. I always try to avoid using Any(). For example Map(...) method should return empty sequence for empty input sequence, so no need to check Any() at all.
@jsonk11 ай бұрын
Starting C#12, you can simply use "return [];" to return an empty enumerable which is extremely nice and less wordy. This would expand to "return Array.Empty()," which "Enumerable.Empty()" uses under its implementation.
@aldul72811 ай бұрын
The main place where I see the default keyword being used and recommended by MS is in Blazor, where you give injected properties default values to imply that they will be injected by the framework and you don't expect them to be null anyways.
@fredericbrown887111 ай бұрын
I absolutely agree, returning default makes the intent less clear and could even introduce a bug in some generic methods that takes both reference and value types (e. g. return default in a async Task, that will return null for reference types and a non null value for a value type). IMHO, you should only use default when you want to get the default(!) value of a type, never because it incidentally is null for a reference type and you want to return null. And yeah, I would normally return an empty sequence when the methods represents a query that can return none, a single or several items. I try to use null only to express "there is no value" and a nullable return type to express "this method might return a value or not", which hasn't the same meaning than an empty sequence in my mind.
@mortenthomas388111 ай бұрын
Hi Nick, I love that you not only talk a bad advice down - you also show us that your own code could be better (returning an enpty collection instead of null)
@iSoldat11 ай бұрын
My preferences are returning default(T) when building generics, the Enumerable.Empty when returning enumerable generics, and null when expecting a single result.
@torrvic115618 күн бұрын
Nick is a very smart boy. If he said to do something then we need to follow his advices undoubtedly 😊
@dnwheeler11 ай бұрын
I agree 100%. A nullable return type means it will return a value or a *null*, not a value or a default. Returning a null is semantically correct.
@Erik_The_Viking11 ай бұрын
Great video with examples of when and when NOT to use defualt or null. I never understood why people try to overcomplicate things.
@mikejs200411 ай бұрын
I’ve killed PRs over someone not returning enumerator.Empty() when the return type is obviously an IEnumerable. Really grinds my gears.
@TheOnlyDominik11 ай бұрын
Agree, use null! There is a difference between returning a result e.g. database query e.g. empty List (Good, but no Match) or null (Error).
@Igahwanoiar11 ай бұрын
This is what the maybe monad is for! (Or optionals, but that is an ambiguous term in other languages.) The main question here is, how do you communicate what happened? Or better yet, how do I provide the caller of the function with enough information to know what to do next? And both null and an empty list will not tell you this (without explicitly stating it in the documentation). The only way you can do this, is by showing it in the method signature. By returning a maybe, it unambiguously states: this method can go well, in which case it has a value, or you have an error. The error is an enum or a custom class that will allow the caller to determine what to do with this error. (Please don't throw an exception; that terrible for performance and software stability!) Some implementations of maybes in C# actually use a collection with 0 or 1 value, so you can just use linq to chain the calls together in your business logic using linq. A match made in heaven! Your business logic becomes a one liner and your code never crashes. (It just takes some getting used to.)
@jhdk35611 ай бұрын
Here is a funny one (if my memory serves me well): int? a = !string.IsNullOrEmpty(str) ? int.Parse(str) : null; // fails, as the compiler cannot find a common type for int and null int? a = !string.IsNullOrEmpty(str) ? int.Parse(str) : default; // in this case, default becomes 0 and not null, because when determining the type of the ternary operator result, it decides that int will work, and default(int) = 0 int? a = !string.IsNullOrEmpty(str) ? int.Parse(str) : default(int?); // This works, as the compiler now decides, that the return type of the ternary operator is int?, which matches the return type of both int.Parse() and default(int?), hence default(int?) becomes null
@DanimoDev11 ай бұрын
Agreed. There is a lot of null hating atm, and some of it is valid when paired with the context, for example using the result or null object pattern instead of returning nulls, or returning empty enumerable instead as you suggested. Of course there are better practices than returning null when appropriate, doesn't mean it is the general rule. The problem I find is that people take the sentiment too literally and apply it to all cases and that it is bad practice, which generally isn't true. I partly blame some of the sensational click bait content creators use in their videos/articles like "DON'T DO THIS" with a picture of something everybody does. Usually a completely false statement until you watch the video in full and understand in what context they are applying the statement too.
@rafazieba998211 ай бұрын
A null and an empty collection are two different things. In this case you should return an empty collection but this is not always the case. E.g. if you have a method that accepts a parameter to search by and you want to return a related list (you want to return all post posted by a given user) then an empty collection means no post authored by this user but null means there is no such user. The example is not perfect because you should probably use an exception or some Optional or Result type here instead of null but nulls are useful. A null and an empty string are two different things. Don't throw ArgumentNullException if string.IsNullOrEmpty like Microsoft does in some cases.
@obiwanjacobi11 ай бұрын
I use default only with generics. Agree on returning non-null (empty) values as much as possible - also think of returning and empty string instead of null. Next video: if (obj == null) - or - if (obj is null) 😉
@hernanar364711 ай бұрын
The video about "X == null" or "X is null", is the null checking evolution I think
@TrostanYT11 ай бұрын
He already has a video on this kzbin.info/www/bejne/raKnip1ml8qSpck
@7r4k1r10 ай бұрын
In the "GetBankDetails" example we could have easily avoided the "if" completely, instead of explicitly returning an empty enumerable, because the result is only being mapped - which should be an operation without any side-effects. When it comes to the "AClass" example at the end, I really like the new "require" modifier which makes the ugly "null!" or "default!" assignment a thing of the past. As always thanks for the videos, officer. :)
@AbhinavKulshreshtha11 ай бұрын
This is how we do it in my office, everything is in a list. I found it bad initially because in many places, I knew we only have one item to send, but eventually i realised its benifit on a large scale project.
@CRBarchager11 ай бұрын
I completely agree with you, Nick. This is terrible. You basically need to think twice of that is returned and have to know what ever type result to from a its default value. I'm always try to get rid of null when ever possible as to lower the need for null checks. Better to have an empty array or list so the calling method can just go and interate over the collection when it's returned even with 0 items.
@NateRocks11 ай бұрын
I'm so glad you pointed out the advantage of doing Enumerable.Empty! If only more people realized this.
@MrMediator2411 ай бұрын
Last one is almost Result/Option from Rust, tagged unions. Probably one of the best ways to handle errors since it's clearly and cleanly separates which functions fallible and which not
@bilalakil11 ай бұрын
I use default for generic returns, and also when I want to return a null-like struct (which will usually be accompanied by an IsSet property or something like that which would return false for the default value). I'd rather use default than calling the default constructor or making a dedicated method for returning a null-like version of the struct. I'm happy to use Array.Empty but I don't like Enumerable.Empty because there's no .Count or .IsEmpty property on an enumerable - you'd have to actually create an enumerator to find out whether any objects exist in the enumerator or not. So, for enumerators specifically, I return null.
@mrgc102411 ай бұрын
Enumerable.Empty() returns an instance of EmptyPartition. It implements the IIListProvider interface's GetCount(bool) method that simply returns 0. The Any() method will not create any enumerator if the type implements one of the following interfaces: ICollection (uses .Count property), IIListProvider (uses .GetCount(bool) method), ICollection (uses .Count property). So you can return Enumerable.Empty() and can use the Any() method to check if it contains any element without creating any enumerator.
@bilalakil10 ай бұрын
@@mrgc1024 Thanks for this info! That’s pretty deep and I didn’t know 😂 So many layers, hard to keep up with..
@jasoncox724411 ай бұрын
For Enumerables returning Empty is definitely the right way to go; but how about when you're returning a single instance of a struct type. I tend to distinguish between `AStruct?` and `AStruct` and return `null` explicitly to indicate that the requested item does not exist (as opposed to `default`) where it is appropriate. [E.g. a "NotFound" result]
@michaelkhalsa11 ай бұрын
For ienumerables, return null if error and empty if none For string, return string.empty, but always check for is null or empty when consuming. For values types, return 0, etc. then in the rare cases where you need a nullable value type, it is not lost in meaning. Keep nulls out of the database, except for dates,I.e., always set a default on fields in database itself.
@brianviktor821211 ай бұрын
I will continue to return 'null'. I return 'default' only in cases where I use generic types. I only follow advice I agree on, and using default over null is not it.
@aragorntjuh11 ай бұрын
I like the Enumerable.Empty suggestion, will start using that from here on out
@karlpickett60358 ай бұрын
It makes sense to return a null instead of empty enumeration, if you want other functions to not accept the empty / null value. That makes it a compile time fail instead of a runtime fail/check. For example, calling LogTransaction() on an empty enumeration probably doesn't make sense.
@joshpatton75711 ай бұрын
IMO, there are a few places where either 'default' or 'default(T)' is the right way to go: You already brought up generics, there's also a few patterns where it makes more sense such as 'try...catch', where you won't expect to use the value returned if the try fails. In this case, the explicit null/zero/whatever is a distraction because in the normal usage we are going to ignore the value returned, and thus do not care. Using 'default' hints at that. default vs default(T) is more about readability in my opinion - use default only if what you are going to be returning is explicitly obvious from context, or when in normal usage you do not care about that result. Fully agreed that returning null collections of any stripe are problematic, I can't count the number of times where I've inherited code with that particular landmine.
@garcipat11 ай бұрын
I mostly use it in default values of a method if argument is optional but i want it prefilled
@NZTritium11 ай бұрын
good tip on returning the empty enumerable.
@winchester258111 ай бұрын
Honestly, I was waiting for this tip nervously, but in the second half of the video it went OK Nick did a great job of explaining about null vs default thing
@sasukesarutobi386211 ай бұрын
I expect a lot of people would have chosen the original solution simply because they know that "null is bad", but don't realise they're often choosing a less obvious null, so they're hiding the problem rather than making the change they want. Returning an empty collection is a much nicer solution as it preserves the expected type. I'd also suggest either defining some error type that gets passed back and/or using task results if you do want to communicate some error information. That way, you have something explicit that you can check for rather than expecting calling code to know what sort of errors they'll need to handle.
@narumikazuchi11 ай бұрын
I just want to correct something (if I understood Nick correctly here). default for structs can NOT be changed. default will always be uninitialized. Meaning a struct with a field like public int X = 42; will only have the 42 in there if the constructor is called. A freshly initialized array of that struct will still only contain structs with X = 0 for all elements. The same is true for the default keyword. And yes, the same is true if the default constructor of the struct assigns values like public Struct() { X = 42; } will still have X = 0 when using default. default for structs is basically all fields zeroed.
@parlor311511 ай бұрын
I think he meant the .NET team changing the behavior of the keyword. And if you expect it to resolve to null and write your code with the assumption, but in .NET 10, it returns something else, then you'd have to make drastic changes before upgrading to the newest runtime version
@bilalakil11 ай бұрын
Note that you cannot actually write public int X = 42 in a struct. You also cannot write a default constructor.
@narumikazuchi11 ай бұрын
@@bilalakil Sure you can. It's been a feature of the language since C# 10.
@bilalakil11 ай бұрын
@@narumikazuchi Interesting! I'm a Unity developer, and Unity's stuck in C# 9 lol. Jealous.
@kurokyuu11 ай бұрын
I mainly use the default cause for me it's nicer, and for collections I've learned from another video from you, that'll return a empty result with Enumerable.Empty or Array.Empty is a good thing, which made really sense. For the default case I understand the argument and can see where someone can have issues I didn't think about especially if you're working in a team where not everyone understands this. Still I'll use default anyway, but the advise itself on this linkedin page is in general dumb as many of these "advises". Since we've got pattern matching I also use something like this: if(item is { }) instead of if(item is not null) or if(item != null), I think the object notation is a bit more beautiful, since in pattern matching you'll eventually also use something like if(item is {IsValidated: true, Date.Year: > 2022}) so it's a bit more consisting but this can be confusing too. At the end of the day it's often a personal think.
@ErazerPT11 ай бұрын
Do agree with the first part, not so much with the second. If you return "something empty" so that "poor lill baby coder" doesn't have to null check, you now can't tell whether or not it was really an empty result set or, erhmm, null. That said, if performance isn't "cycle and or byte critical", i rather use a message passing class that carries the result, status of operation and some info. Sure, there's a memory and performance hit, but for some environments, actionable information will always beat a few ms and MB.
@Sayuri99811 ай бұрын
I don't necessarily agree on not returning nullable enumerables. There is a difference between error and no results. I would return an empty enumerable if and only if there are no results. If a method can fail, I would rather return null or a OneOf. Exceptions are evil and should be avoided because they make a mess of code flow and adds tons of verbosity in my opinion, hence I prefer return types to contain the error.
@MonochromeWench11 ай бұрын
The only time i'd ever use default is in generics. Using default on a Nullable value type seems like asking for confusion and a good reason why you shouldn't always just use it (you get null, not zeroed struct). If you mean null, use null. The difference between the behaviour between reference and value types also a good reason not to use it. Explicitly using null for refence types and new for value types seems like the less confusion option. Its a good idea to make your intent clear.
@MisterFusion11311 ай бұрын
I came here to argue when I saw the title 😂 this is perfect
@tanglesites11 ай бұрын
That is a little crazy! I was just talking about this yesterday! I even tweeted it... X'ed it... whatever. My question wasn't so much about returning default in methods, I build API's and we do that here, ... it was more about assigning it to variable definitions. Stack Overflow said to use default, but others have said null is better. So I was just wondering. This kinda answered my question. Great video Nick.
@Thial9211 ай бұрын
Imo default should only be used for initialization of nullable types when using var like "var something = default(SomeDto);" because you might only want to assign the actual value based on a condition, or "var something = default(T);" when you are handling generics. Using default to assign actual values as in for example "return default" or "something = default" can be highly misleading and dangerous.
@anonimzwx11 ай бұрын
I think empty data struct is the best for methods that return a data struct like a list, null for single item which are nullable and default for the others.
@berrigo211 ай бұрын
I see the "Propery {get;set;} = default;" gets spit out when you use scaffolding with EF6 to generate CRUD pages. Any idea why they stick it in there?
@evancombs515911 ай бұрын
My guess is for primitive types that are not nullable. It is generic code so they do not necessarily know the type, and some types cannot be null.
@zbaktube10 ай бұрын
If a developer cannot decide whether to return null or default, that developer should throw an exception 🙂 I prefer return things that lessens the possibility of a bug. In this case of the enumerator, I would go for the empty one. But in general I would ask around about railway oriented programming among teammates...
@DisturbedNeo11 ай бұрын
Also worth noting that the default value of a nullable value type is null, not the default for the underlying type. Meaning: int i = default; // 0 int? j = default; // null It does make sense, but it’s another little gotcha supporting the argument against using default.
@mirrorless_mirror11 ай бұрын
Totally agree with Nick.
@kiwiproductions451011 ай бұрын
I would love it if somewhere for things like classes I could define what 'default' actually is.
@a__guy11 ай бұрын
no mention of new required keyword when talking about “= null!” and “= default!” 😢
@fifty-plus11 ай бұрын
Yeah, or init-only properties. I guess to limit the scope of the video as they're touched on in other of his videos.
@parlor311511 ай бұрын
Why not pass "entities" as is to the mapper? Or amI missing something?
@Denominus8 ай бұрын
Ha, a bunch of my pet hates crammed into one code snippet: 1. Repository Pattern. 2. Returning a null IEnumerable instead of an empty one. 3. Automapper. Not that I would use default here either, but it's lower on my list of bad practices than the above.
@billy65bob11 ай бұрын
I like default quite a bit. I mainly use it to make my generics even more generic, so I can handle both reference and value types in one class/method. I actually found it really annoying when I had to roll separate ones for each... The main other thing I use it for are for optional parameters, e.g. the CancellationToken on my async methods. That said, these examples are bad, and the person who posted them should feel bad.
@Noceo11 ай бұрын
I am all in for reducing the use of `null`, but not at any cost. I have seen code become wildly complicated, in an attempt to avoid `null`. And while `null` is definitely sub-optimal, it's far from the worst thing you can do.
@wobuntu11 ай бұрын
In my opinion returning null on a method which returns an IEnumerable should be marked as a warning by default in all IDEs. We even forbid that in our team and it prevents you from lots of unnecessary bugs and keeps the caller code more concise
@Max_Jacoby11 ай бұрын
Somewhere I read that "default" was invented for generics when you don't know the type of T. So default could be null or 0 depending on T. If you use default outside generics then you are using it wrong.
@isnotnull11 ай бұрын
public string FirstName {get;set} = default! What do you prefer instead? I usually assign an empty string to avoid null reference warnings
@Astral10011 ай бұрын
I turn off null checker and live a happy life
@djp_video11 ай бұрын
This is the same reason I stopped using the 'var' keyword in most situation -- you can't tell at a glance what the code is doing. Makes debugging so much harder! I hate having to decipher someone else's code when it's littered with 'default' and 'var' and other keywords that make the data types ambiguous. But you and I disagree on one thing... I do return nulls in some (not all) of my methods to indicate an error condition instead of creating and throwing an exception. Exceptions are overused in my opinion. Not just because of the performance hit, but try...catch blocks messy up the calling code more-so than a quick null check. Exceptions are appropriate in many situations, but just to indicate that required data is unavailable isn't usually one of them. Using nulls is standard practice in my code, so I already check for it anyway, and the null coalescing operators make it much easier to do.
@Grigorii-j7z11 ай бұрын
Null for me is more expressive for reading. Also if we dealing with non-reference types I found it more ambiguous: is default value was returned because it's supposed to be default or it was returned as a result of internal check according to business logic?
@margosdesarian10 ай бұрын
Wow i never knew there was such a thing as Enumerable.Empty ... thanks Nick
@fifty-plus11 ай бұрын
If people are using the keyword they should know its intent and the value it would imply. I don't see that people not knowing as a good argument, that's just a lazy programmer not knowing their craft. A better argument is to know when to use default and, in this case, not use null in the first place or if you have too for some unknown reason, use it properly knowing what it does. I like this series, Nick, it makes people aware of all the terrible advice that gets upvoted and hopefully triggers something in them to learn their craft more thoroughly and avoid using a search engine or LLM as their first reference point.
@yakovkemer506211 ай бұрын
Depends on the case, for list - maybe it is a bad idea, but for single record it is always good to throw not found exception. IMHO.
@PierreH196811 ай бұрын
Thank you, Great Advice!
@ocin_the_ocin876611 ай бұрын
this has changed my life
@alonmore2811 ай бұрын
Agree with your video. Generally I don't much understand the use cases of the default keyword. Setting a default value to some variable should be relevant to my app and I shouldn't just use a keyword. For example, having a default int value for one of the properties in my class, where 0 (the default) might actually have a meaning in the context, this may cause conflicts. Also, definitely avoid returning nulls when possible. Generally speaking, if you are able to anticipate different scenarios in your code, you should have them all handled correctly. Returning null may be ambiguous with the reason null was returned, for example. When a method need to return a collection, and a valid scenario caused that there will be no results, just return an empty collection instead of null. By the way, I am not familiar with the " = null!" Syntax. What is the meaning of the exclamation point in the end?
@Esgarpen11 ай бұрын
I will die on the "Don't return null in any way shape or form - ever" hill.
@Astral10011 ай бұрын
And as you can see by the likes, you will die there alone.
@rik090411 ай бұрын
good topic. for me default is not great thing, Im not sure but I thing that there are null for custom struct to, so here the logic of it is broken. I try to not use null in my code, but sometimes it is a best way. I remember in past there was this talk about, don't return null, return object even if it is empty, but this approach can be even worst, it is fine for collection, but for object you just get a mess. I thing programmers should have only one rules, 'every rule is suggestion'. There will be always some edge case where rule will make program worse
@AlFasGD11 ай бұрын
In C# 12 you should be able to use [] instead of the long empty enumerable expression, though I didn't see Rider recommending this
@gamedev_expert11 ай бұрын
upgrade rider version
@IssaFram7 ай бұрын
5:08 is the important part of this video
@MaximilienNoal11 ай бұрын
Default means null for reference types, lol.
@berry21211 ай бұрын
Null IS the default
@burtonrodman11 ай бұрын
🤦♂️. default is NOT the same as null… in fact default is most often the WRONG value when null is an option. in terms of modeling data, null means “unknown”… default is a KNOWN value that is WAY too easily mistaken for valid data. please don’t model your data wrong just because you can’t be bothered to acknowledge all possible states (including unknown)
@sanetby11 ай бұрын
agree, returning null is a bad practice indeed, but default is not a cure, you're just hiding the problem deeper and a hidden problem is much worse than an obvious one
@iamnietzsche733411 ай бұрын
Imo, if the method has a nullable return type, it's just a clear contract, you either get something or null. Ideally I'd want an Option type in C# like some other languages do, in that way it's more enforced.
@evancombs515911 ай бұрын
I see little difference between Nullable and Option?
@Silentsouls11 ай бұрын
If you promisse an IEnumerable, then it should not be null. For when it gets used in linq queries, you do not want an exception for returning null. default has its place, just like with everything in C#, not always everywhere.
@StrangerOks11 ай бұрын
Strange that the memory allocation issue is almost not discussed here in case of returning of Empty Array(or List). Taking into account that this code is returning object collection with potentially big amounts of fields. In general for me, the usage of "default" is suspicious, because each time I would like to check what is returned. And that takes unneeded additional time. About the null, if you call a method that returns reference type I would always expect to check the null in the result. From other side, if I make such a method - all the behavior and returned edge cases should be described in the annotation. Including Exceptions, Nulls, Empty or unknown results. With nullable type support in the latest C# this becomes easier, but I would still like to see good annotation explaining what case is actually cause returning of null.
@andersborum926711 ай бұрын
I have to disagree on this one; as you said, default is just syntactical sugar (i.e. this discussion is entirely about readability), and if you're writing functions that doesn't fit the screen (which you shouldn't), it's all comes down to habit and preference. I can obviously read both types of implementation but find that the default keyword comes across as a bit more expressive. As for returning null (or default) for methods signatures returning enumerables or iterators, just don't - again, agree entirely on this one; however, would use the ternary operator in the return statement.
@garcipat11 ай бұрын
This can also be dangerous. Use null if you want to bw explicit. It is should be treated as a valid value, not just as not assigned.
@Astral10011 ай бұрын
never seen this advice. thank god
@TheWarTurkey11 ай бұрын
I guess it depends on your codebase. In my case, I add and remove types from my codebase and swap between `class` and `struct` all the time, so `default` works best for me.
@fifty-plus11 ай бұрын
That's potentially, without knowing your codebase, a good reason not to use default. It can drastically, unintentionally change meaning under refactor and introduce numerous subtle bugs.
@TheWarTurkey11 ай бұрын
@@fifty-plus That makes sense, but I haven't had an issue with my code base.
@ricardopieper1111 ай бұрын
While I agree the advice is stupid, the statement "how am I supposed to know that?" at 3:51I don't think it's valid in that context. If you're a professional C# dev, you're simply supposed to know this because you studied the language. I agree with all the other points.
@haxi5211 ай бұрын
I don't really agree, no problem with returning `default` vs `null`, it's a similar argument to `var` vs `type`. But I think you should emphasize avoid returning null, regardless of return type, IEnumerable or otherwise.
@woocaschnowak11 ай бұрын
Are you actively looking for those samples, or do they appear in your feed? Cause I don't know if I have my LI feed broken (or quite the opposite ;-)) but I don't see to much programming advices, let alone "Code Cop" candidates 🙂 And yeah, returning empty collection is waaaay above returning null collection.
@MarkCastle10 ай бұрын
What about passing optional Params eg , CancellationToken cancellationToken = default
@mattfbk11 ай бұрын
In my latest project I gave the concept of ResultT and OptionT a try and liked it so far 😊 to be honest I'm not even sure what that null was supposed to mean in this example 😅
@Ext3rmin4tor11 ай бұрын
The Option data type is certainly the best choice as the type checker will ensure that anyone MUST handle having or not the value, and it's the only type safe way of handling values that may or may not exist. You can even overload the linq syntax to have a declarative way of composing operation involving optional values without the need of explicitly handling the existence check at every step.
@Megha-f7d11 ай бұрын
Can you provide me a good resouce to learn microsoft SQL?
@SG_0111 ай бұрын
There is also the difference between returning default and a new struct. Returning default may in fact return an invalid struct, which is not at all clear
@RobinHood7011 ай бұрын
One thing that struck me as you were showing different return types is what if it's "bool" originally and you return default, but then later you change it to a tri-state return type of "bool?", like handling nullable boolean database fields, for example. Your code logic has then changed, but did you really mean it to or did you actually want to return a hard false? That depends on the code, of course, but it's something that would be easy to miss by using default. Also, junior devs might not even know whether the default would return null or false in this situation.
@F1nalspace11 ай бұрын
The only thing i ever use default for is in generics, everything else uses an explicit type.
@shumito11 ай бұрын
essentially is the same reason why I hate "var" . I prefer being explicit
@evancombs515911 ай бұрын
To me the default keyword is a half-baked keyword. Default is a keyword that should be used to help us generate more robust code in a cleaner way. Instead we just have this confusing keyword that looks better than using null, but the reality is in the majority of cases it is just another null. Null should not be the default value of a class. Default should be a class state that we can define and check against. For backwards compatibility reasons, null should only be the fallback state if no default state has been defined.
@birdasaurusrex11 ай бұрын
Default is a good abstraction for generics. However, in general, I don't like using it. :)
@Athurito11 ай бұрын
1 min into the video i am like why should i return null or default instead of an Enumerable.Empty and if he uses EF core he always has a reference and the list cannot be null
@nevett11 ай бұрын
99% of the time the absence of a result from a get method should be an error. If you can provide a cheap way to check for likely success before executing a get method, then do it e.g. and Exists() method. If you can't, then include a success status code in the response. I wouldn't say "never return Null" as it has its place in high performance systems, but it should generally be avoided.
@lextr31109 ай бұрын
if your return type return a nullable.. what is the problem? the caller know it could return null.. so you check for null first when using the result..
@DiomedesDominguez10 ай бұрын
I mustly return null or a Not Found implementation.
@knixa11 ай бұрын
only place I ever really feel okay with default is when there are optional CancellationTokens being passed in
@JohanNordberg11 ай бұрын
I think I've only used "default" as a default value of an argument / prop. Avoid being fancy at all cost.
@shoooozzzz10 ай бұрын
Take a play from functional programming and use an "Option" or "ValueOr". In this example, the repo would return one of two things: (1) the entity requested (2) an error Boom! All cases are covered. No exceptions or exception handling required because the system can handle both paths.
@schk311 ай бұрын
5:12 "Don't return null"
@michael40card11 ай бұрын
Yay, Enumerable.Empty for the win! I completely agree with all of this! Niggle: why return e.empty within an .Any if check at all if the EF result is already an empty collection 😅
@charclay11 ай бұрын
Why not return new()?
@austin.valentine8 ай бұрын
Nick is right. That’s garbage. Also, how do you different an absent value vs an existing value that matches default value for that value type?
@lordmetzgermeister11 ай бұрын
The advice is stupid, using default instead of null doesn't produce better code - it's more of a style decision. I don't think it really matters what you use, if you use it consistently - meaning, you don't have to care, what the default is, if you replace null-checks with default-checks. But then null propagation and null-coalescence don't really work and nullable reference types kinda get in the way and it starts to get annoying. I'm sure there are some devs that don't like using the inconspicuous question marks and prefer full if-blocks. I just try to not return null where possible. Whenever you have to return null or empty value it usually means there was a serious issue in the code execution - either input validation or some kind of business logic fail. In a higher level code I'd rather consider throwing an exception, but it depends whether it's a library or a web API.
@Astral10011 ай бұрын
You would rather throw exception than return null? Oh boy.
@brianparker485810 ай бұрын
Meh! I started using null then ran into problems using null with generics, I then switched to default(T) the lazy programmer in me doesn't think about using both... I think with practice and exposure of its usage its much like "var" usage. If the type is obvious, it's fine to use. Its an interesting argument it doesn't tell you the type... "null" doesn't either...