Are these pass-through checks necessary?

I have listed five different scenarios that, I think, zero verification is necessary in the product code. Although, most of the reference books that I checked do NOT carry out such checks. It is prudent to ignore those checks, while the original link tries to deliver other important ideas. Here I summarize all my considerations as follows and please correct me if there are errors.

class Student
{
    public string Name { get; set; }

    public Student(string name)
    {
        Name = name;
    }

    public Student() { }

    public override string ToString()
    {
        return string.Format("Name: {0}", Name);
    }
}

class StudentNameComparer : IComparer<Student>
{
    public int Compare(Student x, Student y)
    {
        if ( (x == null) || (y == null) ) // <C1> Should we check there?
            throw new ArugmentNullException("bla bla");

        return x.Name.CompareTo(y.Name);
    }
}
////////////////////////////////////////////////////
List<Student> students = new List<Student> {
    new Student("s1"),
    new Student("s4"),
    new Student("s3"),
    new Student("s2")
};
students.Sort(delegate(Student x, Student y) 
    { 
        if ( (x == null) || (y == null) ) // <C2> Should we check there?
            throw new ArugmentNullException("bla bla");

        return x.Name.CompareTo(y.Name);    
    });

////////////////////////////////////////////////////    
List<Student> students = new List<Student> {
    new Student("s1"),
    new Student("s4"),
    new Student("s3"),
    new Student("s2")
};
students.Sort( (x, y) => 
    {
        if ( (x == null) || (y == null) ) // <C3-1> Should we check there?
            throw new ArugmentNullException("bla bla");

        return x.Name.CompareTo(y.Name);    
    });
Or
students.Sort( (Student x, Student y) => 
    {
        if ( (x == null) || (y == null) ) // <C3-2> Should we check there?
            throw new ArugmentNullException("bla bla");

        return x.Name.CompareTo(y.Name);    
    });
////////////////////////////////////////////////////    
List<Student> students = new List<Student> {
    new Student("s1"),
    new Student("s4"),
    new Student("s3"),
    new Student("s2")
};
foreach (Student std in students.OrderBy(p => 
    { 
        if (p == null) // <C4> Should we check there?
        {
            throw new ArgumentNullException("...");
        }
        return p.Name;                
    }))
{
    Console.WriteLine(std);
}
+3
source share
1 answer

Ok, just take a look at the interface in the documentation .

In fact, what is being done there is IComparerwrong.

The preferred implementation is to use the CompareTo method of one of the parameters.

null IComparable. null .

Compare() , null.

, Sort , , null .

, . , . null, , . , , null.

-

p => p != null ? p.Name : string.Empty

( , null).

+4
source

All Articles