How to create instance of class that get data from 2 another instance?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jan 3 22:08:11 PST 2015


On 01/02/2015 12:42 PM, Suliman wrote:

 > auto seismodownload = new seismoDownload(emsc_csem, this);
 > then:
 > auto mysql = new MySQL(parseconfig,eqs);
 >
 > So could anybody show me better way?

Yes, there is a better way.

 > As I said I did not fully understand how use global class instance...

One good thing about D is that globals are better than other languages 
because they are actually module-global and by default thread-local. 
Module-global means that there more than one module can use the same 
name for their respective globals; thread-local means that implicit 
data-sharing is prevented.

However, module-globals can be harmful as well because depending on the 
design, they prevent functions from being reentrant and prevent having 
more than one of that resource.

For that reason, it is usually better to provide the resource to its 
consumers e.g. as constructor parameters.

Instead of this:

string fileName;    // <-- May be a problem

static this()
{
     /* Just to assume that we need a run time value. */
     import std.random;
     import std.string;
     fileName = format("file_%s", uniform(0, 1000));
}

struct S
{
     void foo()
     {
         /* Assume that it uses fileName. It would be at least
          * confusing if there were more than one instance of
          * S. Which one would be using fileName when? */
     }
}

void main()
{
     auto s = S();
     s.foo();
}

Prefer this:

struct S
{
     string fileName;    // <-- Takes it as a run-time argument
                         // (Could be constructor parameter as well.)

     void foo()
     {
         /* Now it would be using its own fileName, which might
          * be provided to more than one object but then it
          * might be acceptable, presumably because it was
          * according to design. */
     }
}

void main()
{
     import std.random;
     import std.string;

     auto s = S(format("file_%s", uniform(0, 1000)));
     s.foo();
}

Ali



More information about the Digitalmars-d-learn mailing list