命名引數避免了可選引數的錯誤

始終將 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");