Fluent Interfaces - Mini DSLs
30 07 2007Anders Noras writes about what he calls an “embedded DSL” for some calendar components work he has been doing.
ToDoComponent planningTask =
Plan.ToDo("Plan project X")
.StartingNow
.MustBeCompletedBy("2007.08.17")
.ClassifyAs("Public");
planningTask.Save();
Not what usually comes to mind when I think of DSLs, but it’s still interesting. The calendar components use a construct called a Fluent Interface, in which the methods on an object return an instance of the class they are defined in, allowing actions performed on an object to be chained, as in the example above.
This is a very useful construct that is used in frameworks such as Hibernate / NHibernate. I’ve never really thought about using fluent interfaces to create a sort of pseudo-DSL, and I’m not sure yet how useful this would be with the types of domain entities I write in my day job, but this has got me thinking.
(EDIT: Closing comments due to heavy spamming)