chaining

grauzone none at example.net
Thu Feb 26 00:45:28 PST 2009


Brian wrote:
> I want to use a chaining system for easy setting of object attributes, 
> which would work great for a single object, unfortunately derived classes 
> cannot inherit the chained functions implicitly, whats the best way 
> around this?
> 
> class Base {
> 	int x;
> 	Base foo(int x_) {
> 		this.x = x_;
> 		return this;
> 	}
> }
> 
> class Derived : Base {
> 	Derived bar(int y_) {
> 		return this;
> 	}
> }
> 
> // usage:
> auto m = (new Derived).foo(10).bar(x); // bar can be accessed through foo

Couldn't you just write the above example as:

auto m = new Derived;
m.foo(10);
m.bar(x);

This is actually much more readable: the reader doesn't need to know 
that the functions foo and bar return m; instead, the code uses m 
directly. Obviously, this is also simpler to implement than chaining.

I don't get why some people like chaining. Unlike in languages like C++, 
you can always use "auto" to keep the typing to a minimum. What more 
arguments are there for chaining?


More information about the Digitalmars-d-learn mailing list