How about Go's &Struct instead of new? addendum
Justin Johansson
no at spam.com
Thu Nov 12 13:03:33 PST 2009
Justin Johansson Wrote:
> Currently in my D projects I use static opCall to eliminate "new" (at least for
> classes) such as:
>
> class Foo
> {
> int x;
> Foo( int x) { this.x = x; }
> static Foo opCall( int x) { return new Foo( x); }
> }
>
> I'm not sure if this considered good D style of not (please advise), but it does
> eliminate having to type new all the time to allocate and construct new Foo's.
>
> However, for consistency, I find myself often typing in static opCall boiler-plate code
> when creating a new class definition even for classes which few instances are
> ever created in the wild. In some cases, then, more overall keystrokes are
> incurred just to save the infrequent new keyword when instantiating the class.
>
> Analysing the break-even point (minimum number of new's to save) for the
> static opCall keystroke overhead is (at least in this case) .. hmm .. let's see ...
>
> "new" is 3 characters but at least one whitespace separator is needed so that
> makes 4 characters "new ".
>
> Now the following comparison text (edited in fixed-width font, 1st line is 50 chars; 2nd is 48):
>
> static Foo opCall( int x) { return new Foo( x); }
> new new new new new new new new new new new new
>
> Whilst I like the idea of getting rid of new keyword, I must admit that on the
> balance I generally don't save any keystrokes using the static opCall instrument.
>
> btw. My thinking for getting rid of new keyword came from some experience
> with Scala case classes and companion classes (Object in Scala parlance).
> From what I understand/remember, "Object" is Scala's way of getting rid of "static" in
> relation to class member variables and methods. In some ways, D opCall some analogy
> with these Scala idioms.
>
> What do others think?
>
I neglected to say also that my usage of static opCall for classes is mostly in relation
to immutable "value classes". If there's already a precomputed instance of the same
class with the same constructor parameters my static opCall returns the precomputed
instance and not a new instance. *In this case*, it's not a matter of saving keystrokes
but a reflection of my design so I guess that makes my usage of static opCall more
of a necessity.
Justin
More information about the Digitalmars-d
mailing list