Named Arguments avoids bugs on optional parameters
suggest changeAlways use Named Arguments to optional parameters, to avoid potential bugs when the method is modified.
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
The above code compiles and works fine, until the constructor is changed some day like:
// 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");
Best practice to avoid bugs when “someone else in the team” made mistakes:
var jack = new Employee(name: "Jack", title: "Associate");
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents