Why do private member variables behaved like protected in the same module when creating deriving class?

Neia Neutuladh neia at ikeran.org
Thu Nov 1 05:01:00 UTC 2018


On Thu, 01 Nov 2018 02:44:47 +0000, unprotected-entity wrote:
> On Wednesday, 31 October 2018 at 20:46:05 UTC, Zot wrote:
>> On Monday, 29 October 2018 at 09:25:07 UTC, unprotected-entity wrote:
>>> Just how often does one need to access the private members of a class,
>>> within a module?
>>
>> a lot actually. e.g. unittests
> 
> that does not compute.
> 
> all you are doing is further coupling unit-tests, with all the other
> crap that is already coupled in your module.

If I'm writing larger-scale tests, I want them to be durable to code 
changes; those tests are about exercising the code in the same way as a 
consumer of my library would.

The types of tests I'm writing that might need access to private members 
are generally pretty short and focused, and they don't test the library as 
I expect consumers to use it. They're likely to be testing a private 
function opaquely, not examining private variables in a class. And if I 
change the function, I probably need to change the tests.

> and why is it so hard to put the unit test inside the actual class?

class Foo(T)
{
  unittest {}
}

That test might never get run with `dub test`, and it's going to get 
compiled into every instantiation of the type in every consumer of my 
library. That's kinda bad.

There *is* a workaround. Where you would write:

    class Foo(T)
    {
    }
    unittest
    {
      new Foo!int;
    }

You instead write:

    class Foo(T)
    {
      version (MyLibraryTest) static if (is(T == int))
      unittest
      {
        new Foo;
      }
    }
    version (MyLibraryTest)
    unittest
    {
      // force the template to instantiate
      Foo!int f;
    }

That's a lot easier to mess up, so I'd rather use the short version.


More information about the Digitalmars-d mailing list