Code-review is important in our daily development. Some developers may spend lots of time on learning new features of the languages, DDD, distributed system or some fancy stuff but the first thing we should keep in mind is we need to write the robust, maintainable code. Here are some tips from my recent code-review and I hope it would be helpful for you.

Image for post

NullReferenceException series

The NullReferenceException is really annoying. The best way to avoid it is to check if the variable is null before you use it. Here are some potential issues. I also include other exceptions such as ArgumentNullException here.

Always initialize the collection when you declare it

One common error is sometimes we declared a collection but did not initialize it before using it. Like this:

List<Person> persons;
// Some logics
// If you use persons directly you may got a null object

So the better way is to always initialize the collection when we declare it:

List<Person> persons = new List<Persons>();
// Then you can do something as usual

Especially if we have a property which has its own private field:

// It is good to initialize the private field when we declare it.
private ObservableCollection<Person> _personList = new ObservableCollection<Person>();
public ObservableCollection<Person> PersonList
{
     get => _personList;
     set => SetProperty(ref _personList, value);
}

DO NOT return null values from methods returning collections

Another tip is if we have a method that returns a collection, do not return null. Instead, if there are no satisfied elements, we should return an empty collection.

public List<Person> GetPersons()
{
    // Some logic to retrieve the objects. If not found, then return an empty collection. DO NOT return null.
    return new List<Person>();
}

FirstOrDefault() or First()?

LINQ has some similar methods like First() and FirstOrDefault(). The key difference is the behavior for the empty collection. If the collection is empty or there is no element that satisfies the condition, then First() will throw InvalidOperationException. For this case, FirstOrDefault() is safe because it can return a default value for an empty collection or no element satisfies the condition. But we should be truly clear if the default value is null - that is another reason which would cause NullReferenceException - **The default value for reference and nullable types is ****null**. So it would be better if we do like this:

var firstPerson = persons.FirstOrDefault(x => x.Age > 18);
// Check if the variable is null
if (firstPerson != null)
{
    // Do something to the firstPerson
}

#code-review #dotnet #dot-net-framework #dotnet-core

My tips for .NET code-review
1.05 GEEK