Friday, October 19, 2007

Fluent Constructors

Something in the following code just does not look right to me.

Employee employee = new Employee();
employee.EmployeeNumber ="1565407"
employee.Name = "Nick"
employee.LastName = "Markovic"
employee.JobFunction = CreateJobFunction("Tester")



The Employee Constructor just tells me nothing on how to use the object.

It does not tell which properties are required and which are not.
In this example EmployeeNumber, Name and LastName were all required but JobFunction was not. To make things worse the employee object has about 20 other properties on it. I came across this problem while I was writing unit tests for legacy code and needed to create a simple employee to pass as a parameter. I had to go digging through the internals of employee to determine which fields needed to be set.
However if the creator of this class had crated a constructor that looked something like Employee(number,firstName,LastName). The interface would be much more fluent and would create much easier to understand code.

1 comment:

Chris Barrow said...

So did you end up refactoring the class to solve this issue? Did you refactor to a specific pattern such as dependency injection?