Non-null objects, the Null Object pattern, and T.init

Michel Fortin michel.fortin at michelf.ca
Fri Jan 17 07:05:12 PST 2014


On 2014-01-17 01:42:37 +0000, Andrei Alexandrescu 
<SeeWebsiteForEmail at erdani.org> said:

> Further avenues are opened by thinking what happens if e.g. init is 
> private or @disable-d.
> 
> Thoughts?

Some more thoughts.

Couldn't we just add a class declaration attribute that'd say that by 
default this type is not-null? For instance:

	// references to A are not-null by default
	@notnull class A {}

	// references to B are not-null too (inherited)
	class B : A {}

Then you have two types:

	A  // not-null reference to A.
	A? // nullable reference to A.

Use it like this:

	A a;  // error: cannot be null, default initialization not allowed
	A? a; // default-initialized to null

	void test1(A a) // param a cannot be null
	{
		a.foo(); // fine
	}

	void test2(A? a) // param a can be null
	{
		a.foo(); // error: param a could be null
		if (a)
			a.foo(); // param a cannot be null, allowed
	}

	void test3(A? a) // param a can be null
	{
		A aa = a; // error: param a could be null, can't init to not-null type
		if (a)
			aa = a; // param a cannot be null, allowed
	}

This is basically what everyone would wish for a not-null type to do. 
The syntax is clean and the control flow forces you to check for null 
before use. Misuses result in a compile-time error.

-- 
Michel Fortin
michel.fortin at michelf.ca
http://michelf.ca



More information about the Digitalmars-d mailing list