loading...

re: No more NullReferenceException for Lists in C# VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Read again: What I said is that in some rare situations it makes sense to distinguish between empty and null collections. In almost all situations ...

I'm not claiming that the approach of this article is the best solution or following the best practices , just a demonstration of a prototype of a possible better approach. About writing simple and profiling , it depends on the application , simplicity and clean code are guidelines , not an approach , it always depends , you don't need to bet ,what i have faced in my career or you have is not relevant , the approach should be generic , can you think of any condition which you are adding an item to a collection but Don't want to initialize it ?
Because i don't think there is , therefore i believe the first addition should handle the initialization

I feel like you're being intentionally obtuse about this when everyone else has provided great arguments in favor of always-initializing collections.

To play your game, here's an example:


class LibraryVisitor {
  private List<Book> CheckedOutBooks { get; set; }
  private string MemberNumber { get; set; }

  public void CheckOut(Book book) {
    CheckedOutBooks.Add(book);
  }

  public void Register(memberNumber) {
    MemberNumber = memberNumber;
    CheckedOut = new List<Book>();
  }
}

This is obviously shit code (arguably no worse than your examples), but the premise is I shouldn't be able to check out a book until I've registered.

A reasonable fix to this code would be:


class LibraryVisitor {
  private List<Book> CheckedOutBooks { get; } = new List<Book>();
  private string MemberNumber { get; }

  public void CheckOut(Book book) {
    if (MemberNumber == null) {
      throw new NotRegisteredException();
    }

    CheckedOutBooks.Add(book);
  }

  public void Register(memberNumber) {
    MemberNumber = memberNumber;
  }
}

When you don't get , you don't get it.
let me demistify once more.
The conventional methods which any junior developer should be aware are crystal clear . The issue is why when you are trying to add to a list which is a member of a class and you already instantiated the class should throw an exception ?
It should instanciate the list object on the first add itself.

code of conduct - report abuse