www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Is this a good way to do lazy evaluation?

reply Jack <jckj33 gmail.com> writes:
I have a base class that loads a value and if it isn't net, load 
a default value. Since the value can be set, I'd like to do lazy 
evaluation of this default value until it's really needed. So 
rather have a C defValue = xxx, that makes xxx to be loaded even 
if defValue doesn't get used. So I thought I would use property 
and override it from the derived class, to archive the lazy 
evaluation effect that I'd like. Is this a good approach? are 
there better ways to do that? here's a sample code of what I'm 
talking about (I'm using int just to make it simple but the class 
in the real code is bigger and can have many instances, hence my 
attempt to optimize that):

class A
{
	C defValue() { return C.a; }
	C value;

	void doSomething()
	{
                // doSomething gets called from all derived classes
                // but value is set often, loading defValue right 
away
                // would waste time and resources
		if(!value) {
			value = defValue;
		}
	}
}

class B : A
{
         // use propety to have a lazy evaluation of value
	override C defValue() { return C.b; }

	void foo()
	{
		// loadDefvalue, if value not set, lazily...
		doSomething();
		// do something else...
	}
}

class C
{
	int n;

	this(int v)
	{
		n = v;
	}

	static this()
	{
		a = new C(10);
		b = new C(11);
	}

	void load()
	{
		// do something with n
	}

	static
	{
		C a;
	  	C b;
	 }
}
Feb 22 2021
parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 2/22/21 2:00 PM, Jack wrote:

      C defValue() { return C.a; }
Yes, putting the expression in a function is the way I know for lazy evaluation. Ali
Feb 23 2021