Static constructor

ludo fakeaddress at gmail.com
Wed Jan 6 17:05:02 UTC 2021


I read in the documentation
"Static constructors are used to initialize static class members 
with values that cannot be computed at compile time"

I try to understand the design of the following code:

---
class OpenAL
{
	static string[int] ALErrorLookup;
	static Object mutex;

	// Initialize static variables
	static this ()
	{	ALErrorLookup = [
			0xA001: "AL_INVALID_NAME"[],
			0xA002: "AL_ILLEGAL_ENUM",
			0xA002: "AL_INVALID_ENUM",
			0xA003: "AL_INVALID_VALUE",
			0xA004: "AL_ILLEGAL_COMMAND",
			0xA004: "AL_INVALID_OPERATION",
			0xA005: "AL_OUT_OF_MEMORY"
		];
		mutex = new Object();
	}

        static anotherfunc()
        {}

	static Object getMutex()
	{	return mutex;
         }
}
---

At this point, I have not looked up Object, guess must be a 
class. It seems to me that ALErrorLookup can be computed at 
compile time... So the constructor is static because mutex "can 
not be computed at compiled time"?

The idea of the dev (from context) is to that this class will 
just be a wrapper, no instance necessary. So anotherfunc(), which 
does the main work, is static and everything goes this way.

Then getMutex returns the static mutex when necessary... Have not 
looked that up yet either.

But, I don't know, i have a feeling that this is over 
complicated. For example, can't we have AlErrorlook-up 
initialized another way in D, a static mutex in the getMutex 
function directly (with if (mutex == null) {mutex = new Object()} 
.

I don't know, is it the proper D way? And also, when we have 
those classes with everything static, does it even make sense to 
have a class? This module actually contains only this class 
(https://tinyurl.com/yxt2xw23) Shouldn't we have one module with 
normal functions?

ANY input is learning material for me. Thanks.






More information about the Digitalmars-d-learn mailing list