命名参数避免了可选参数的错误

始终将 Named Arguments 用于可选参数,以避免在修改方法时出现潜在错误。

class Employee
{
    public string Name { get; private set; }

    public string Title { get; set; }

    public Employee(string name = "<No Name>", string title = "<No Title>")
    {
        this.Name = name;
        this.Title = title;
    }
}

var jack = new Employee("Jack", "Associate");   //bad practice in this line

上面的代码编译并正常工作,直到有一天更改构造函数,如:

//Evil Code: add optional parameters between existing optional parameters
public Employee(string name = "<No Name>", string department = "intern", string title = "<No Title>")
{
    this.Name = name;
    this.Department = department;
    this.Title = title;
}

//the below code still compiles, but now "Associate" is an argument of "department"
var jack = new Employee("Jack", "Associate");

团队中的其他人犯错误时避免错误的最佳做法:

var jack = new Employee(name: "Jack", title: "Associate");