class instance construction

spir denis.spir at gmail.com
Thu Nov 11 10:38:13 PST 2010


On Thu, 11 Nov 2010 17:57:40 +0100
Daniel Gibson <metalcaedes at gmail.com> wrote:

> spir schrieb:
> > Still, an other case when "new" annoys me is method chaining, because it makes syntax heavier and less readable:
> > 	c = (new C(p)).do(x);
> > versus:
> > 	c = C(p).do(x);
> > Or, maybe, the parser could be clever enough to correctly decode:
> > 	c = new C(p).do(x);
> > 
> 
> Is this really a common case?
> Constructing an object, just to call *one* method on it and then throw it away?

:-) It does not throw it away, instead returns this. And yes, this is common practice. For instance in a PEG matching lib, I want to be able to set match actions to pattern, like:
	realNumber = new Tuple(digits, DOT, digits).setAction(toFloat);
Or even (by overriding opCall):
	realNumber = new Tuple(digits, DOT, digits)(toFloat);
Very practical: it lets one define the pattern in one go w/o sacrigficing readability (well, at least in wy views -- but sure it's dicussable).

> > Second, could there be a default constructor for classes, like for structs? Namely, one that sets declared fields:
> > 	class C {int i;}
> > 	...
> > 	auto c = new C(1);
> > This is one great advantage of static languages, that the compiler knows more thank to declarations. Isn't it sensible to use this knowledge when helpful? I simply find the following stupid (I mean it's job for a machine, not for a programmer):
> > 	class C {
> > 	    int i;
> > 	    this (int i) {this.i = i;}
> > 	}
> > As we already enjoy this feature for structs...
> > 
> 
> Again: Is that a common case? A constructor (probably with multiple arguments) 
> that all just set the corresponding fields of the object?

Depends on coding style, probably. If two element mean something together as a whole, I like to put them together.

> However, I agree that all that this.i = i; is tedious.
> As I have suggested before in another thread (and Simen did in this thread), 
> something like
> 
> this( int this.i, float this.y, Foo f) {
>      // f is no field of the class.
>      this.b = new Bar(f, i);
> }
> 
> would be helpful because you could mix arguments that are just passed with 
> arguments you want to use in the constructor without too much writing overhead.

Yes, I like this very much. It lets clearly tell apart which params are in fact fields, and which ones are params properly speaking.


Denis
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d mailing list