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

Ola Fosheim Grøstad" <ola.fosheim.grostad+dlang at gmail.com> Ola Fosheim Grøstad" <ola.fosheim.grostad+dlang at gmail.com>
Fri Jan 17 06:34:01 PST 2014


On Friday, 17 January 2014 at 14:13:40 UTC, Adam D. Ruppe wrote:
> bool isLoggedIn(User user) {
>     return user is null ? false : user.isLoggedInImpl();
> }

In most cases you can avoid null-related issues if you plan for 
it, but if you adapt existing software you might not afford to do 
the changes. Even simple adaption of a framework can cost many 
weeks of hard work and then you need to keep it in sync with 
future versions of the framework.

I also think there might be cases where you run the null-test a 
lot of times with the same result and would be better without it. 
Like in deep nested data structures where the pointer almost 
never is null, and then a trap with recovery might be cheaper, 
amortized.

Sometimes you can write more efficient datastructures if you ban 
deletion:

Like:
ptr = someobject;
weakcontainer.add(ptr);
...
ptr.setdeleted();
ptr = null;
...
weakptr = weakcontainer.get(id);
if(weakptr.isValid())...;

In this case weakptr would point to the original object before 
GC, and to the init object after GC. Saving space, but not 
requiring changes to the weakcontainer implementation.


More information about the Digitalmars-d mailing list