On Sunday, 4 December 2016 at 20:44:05 UTC, Jonathan M Davis wrote:
On Sunday, December 04, 2016 15:30:22 vladdeSV via Digitalmars-d-learn wrote:
Hello!

I have a question not directly related to D as it is with coding standards.

My issue at hand is if I have one variable for a class, which I
want to be directly accessible for anything else, should it be
  1. public, or
  2. private, with @property get/setters?

From what I have been told is that variables should be private. But if I do not want to make any checks whatsoever when setting a
variable, I see no benefit to the private approach.

Are there any other reasons to use get/setters?



This might not be usefull for ure current usecase but if you want a property to behave like a field, it has to be a field. So a boxed type might be better depending how much you want to manage.
Here are some property like examples:

   struct Prop(T)
   {
      private T value;

      alias opCall this;
      ref T opCall() { return value; }
      ref T opCall(T val) { return value = val; }
string toString() { import std.conv: to; return value.to!string; }
   }

   struct ReadOnly(T)
   {
      private T value;

      alias opCall this;
      T opCall() { return value; } // return a copy
string toString() { import std.conv: to; return value.to!string; }
   }

   struct WriteOnly(T)
   {
      private T value;

      void opAssign(T val) { value = val; }
      string toString() { return typeof(this).stringof; }
   }

// alternative write only so you can chain opCall writeOnly(33)(56)(66);
struct AltWriteOnly(T)
   {
      private T value;

      ref typeof(this) opCall(T val) { value = val; return this; }
      string toString() { return typeof(this).stringof; }
   }

   struct FunProp(T) if(isSomeFunction!T)
   {
      private T value;

      alias value this;
      void opAssign(T val) { value = val; }
      string toString() { return T.stringof; }
   }


   class Test
   {
       Prop!int someVal;
       ReadOnly!string name;
       WriteOnly!int someOtherVal;
       FunProp!(void delegate(int)) funProp;

       this()
       {
           name.value = "Test";
       }
   }

   void main()
   {
       auto test = new Test;
       test.someVal = 66;
       test.someVal++;
       test.someOtherVal = 100;
       test.funProp = (int i) => i + test.someVal;
       test.someVal.writeln;
       test.name.writeln;
       test.funProp(33).writeln;
       test.funProp.writeln;
       test.someOtherVal.writeln;
   }

haven't done extencive tests with them but they can be used as builing blocks, you can add other operator overloads to manage other access to the value.
you can build better properties without @property :/

Reply via email to