Fluent Interface & Method Chaining
ctwardell
Posts: 1,716
With the recent discussion of FORTH I thought it might be worth while to discuss Fluent Interfaces and Method Chaining as they seem to be ways of being somewhat "FORTHlike".
Here are a couple of references:
http://en.wikipedia.org/wiki/Fluent_interface
http://en.wikipedia.org/wiki/Method_chaining
I've recently been working on a C# project that involves reading in large text files and populating an object model with the data in the files.
I was able to reduce code size and improve readability by creating a few extention methods to the .Net String object that allow me to chain together several steps into what is almost like a sentence describing what needs to be done.
I see method chaining as being somewhat "FORTHlike" in that each method call is using the result of the previous call sort of like using the stack in FORTH.
Anyway, hoping not to start any wars, just some discussion.
C.W.
Here are a couple of references:
http://en.wikipedia.org/wiki/Fluent_interface
http://en.wikipedia.org/wiki/Method_chaining
I've recently been working on a C# project that involves reading in large text files and populating an object model with the data in the files.
I was able to reduce code size and improve readability by creating a few extention methods to the .Net String object that allow me to chain together several steps into what is almost like a sentence describing what needs to be done.
I see method chaining as being somewhat "FORTHlike" in that each method call is using the result of the previous call sort of like using the stack in FORTH.
Anyway, hoping not to start any wars, just some discussion.
C.W.
Comments
foo first; second; third.
This calls "first" with the instance "foo", then calls "second" with the same instance, then "third" with that instance. The result of the phrase is the result returned by "third". By contrast,
((foo first) second) third.
This calls "first" with the instance "foo", then uses the value returned as the instance to apply "second" and uses the value that returns as the object instance to apply "third".
Mike,
The first example with the ";" seems similar to VB.Nets "With/End With" structure where you do something like:
With foo
.First
.Second
.Third
End With
Using "." to chain calls in VB.Net and C# is more like you second example where the return value within the parens is the input to the next method:
Foo.First.Second.Third would call the First method on Foo, the Second method on whatever was returned by First, and the Third method on whatever was returned by Second.
These concepts are pretty simple to implement in .Net, I haven't looked at doing anything like this in C or C++ yet.
I know similar concepts are also used in Javascript.
Maybe someone on the PropGCC team can discuss if/how it might work on PropGCC.
C.W.