Monday, October 27, 2008

XNA Series - Refactoring GameObject

By now, our GameObject and GameAgent classes are getting out of hand, we have kept expanding them and now they are not very cohesive. There are several problems I see as I look at the code in front of me at this point:
  • Code Documentation is Pitiful
  • Lots of Public variables
  • Poor class planning
So a little restructuring is in order. First, I am going to copy all the extra methods out of GameAgent and bring them into GameObject. I can live with smart objects. Of course I'll need to change all the references to GameAgent to GameObject, but that is not too bad.

Next I want to move my variables from the access level of public to protected. This means that only objects that are derived from this class can see these variable, everyone who just uses an instance of the class has to get at them through either a method or a property (or not at all).

So for all the variables that need to be viewed outside the class (location, rotation, etc) I am creating a public Property.

Then to top things off, I am adding XML style comments to all my class members. Visual C# has a great shortcut for doing comments, on the line before a class or class member, type /// and it will prefill a template for a XML style comment.

for example, the code

public void SetPosition(Vector2 point)
{
this.position = point;
}

on the line before it, I typed in /// and got

/// <summary>
///
/// </summary>
/// <param name="point"></param>
public void SetPosition(Vector2 point)
{
this.position = point;
}


now I can just fill in my description and the decription for the point parameter. That makes life a little easier. Visual C# also uses XML comments in tooltips when you access that class member in some other area of your code.

You may have also noticed that I moved GameObject out of the class of the current game and put it in my own namespace johnnyGizmo. So when I want to use it in a new game, I just need to add a class from the solution explorer and in my file say

using johnnyGizmo;


Later when I am happy with how the class looks, i.e. it is finished, I can compile it to it's own library for simple use in other programs. You can see the refectored GameObject files Here
Post a Comment