Null Object Pattern

Want to avoid the crazy if conditions in your application and ensure that it does not crash and yet provide a good logging mechanism? Use the Null Object Pattern. You will end up writing in more classes but it will help you make a good stable app.

Imagine you are trying to find something in a hierarchy; lets say a game object. Lets say the method used to find this gameobject is FindGameObject("Avatar") which returns either null or a valid game object. You cannot guarantee that this method will always return a valid game object. So you end up adding a condition like this

GameObject obj = FindGameObject("Avatar");
if(obj != null)
Printf("Do something");

Imagine if the hierarchy is long and you end up nesting the conditions like this

GameObject objRoot = FindGameObject("Avatar");
if(objRoot != null)
GameObject objParent =objRoot.FindGameObject("AvatarMain");
if(objParent != null)
GameObject objChild = objParent.FindGameObject("AvatarChild");

 and so on. You can simplify this by doing the following

GameObject objRoot = FindGameObject("Avatar");
GameObject objParent = objRoot.FindGameObject("AvatarMain");
GameObject objChild = objParent.FindGameObject("AvatarChild");

and you can guarantee this to not fail by having GameObject.FindGameObject return an empty Game Object if the object you are attempting to find does not exist or is null.

GameObject FindGameObject(string objectName)
{
GameObject obj = FindInHeirarchy(objectName);
if(obj == null)
return new GameObject(); // an empty game object instance that has nothing in it.
}

I hope you get the idea. You could wrap this using a nice interface and return a NullObject instance of the class. For eg. return new NullGameObject() and change the return type from GameObject to IGameObject. You can add any log you want to inside the NullGameObject class. This will help you debug the issues.

Comments

Popular posts from this blog

Authoritative Server - MMO

Code dependencies