www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - style question on structs

reply "Jonathan" <jdgall84 gmail.com> writes:
Given a struct

struct Foo{
   enum INT_C {Yes, No}
   INT_C a;
}

-- we wish to make a constructor.  We want to set the answer to 
Yes if we construct the struct with an integer.  There are some 
stylistic choices to be made.

The first choice is: do we use this (I seem to recall being told 
in Java with classes there is debate whether 'this' is 
preferrable or not).

this(int y)
{
   //choice 1:
   this.a = this.INT_C.Yes;
   //choice 2:
   a = INT_C.Yes;
}

The second choice is: do we qualify by the struct name:

this(int y)
{
   //option 1
   a = Foo.INT_C.Yes;
   //option 2
   a = INT_C.Yes;
}

The reason I ask, is that I remember some cases in Java where it 
was advantageous to use 'this'.
Dec 29 2013
next sibling parent "John Colvin" <john.loughran.colvin gmail.com> writes:
On Sunday, 29 December 2013 at 18:58:07 UTC, Jonathan wrote:
 Given a struct

 struct Foo{
   enum INT_C {Yes, No}
   INT_C a;
 }

 -- we wish to make a constructor.  We want to set the answer to 
 Yes if we construct the struct with an integer.  There are some 
 stylistic choices to be made.

 The first choice is: do we use this (I seem to recall being 
 told in Java with classes there is debate whether 'this' is 
 preferrable or not).

 this(int y)
 {
   //choice 1:
   this.a = this.INT_C.Yes;
   //choice 2:
   a = INT_C.Yes;
 }

 The second choice is: do we qualify by the struct name:

 this(int y)
 {
   //option 1
   a = Foo.INT_C.Yes;
   //option 2
   a = INT_C.Yes;
 }

 The reason I ask, is that I remember some cases in Java where 
 it was advantageous to use 'this'.
There is no need to qualify by either of them. If you do want to qualify for readability reasons then "this" would be preferable in my opinion as it will remain correct if you later change Foo to a templated struct.
Dec 29 2013
prev sibling parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 12/29/2013 10:58 AM, Jonathan wrote:

 Given a struct

 struct Foo{
    enum INT_C {Yes, No}
    INT_C a;
 }
[...]
 The second choice is: do we qualify by the struct name:

 this(int y)
 {
    //option 1
    a = Foo.INT_C.Yes;
That's what I do without thinking much about it.
    //option 2
    a = INT_C.Yes;
 }
Going off topic a little, Phobos has something to offer for such Yes/No flags: import std.typecons; struct Foo { Flag!"with_int" a; this(int y) { this.a = Yes.with_int; } } Yes.with_int is a convenience struct. Otherwise, you can type Flag!"with_int".yes and Flag!"with_int".no as well. Ali
Dec 29 2013