Sunday, 21 August 2016
The Rule of Three
The Rule of Three is a simple idea that any time you need to do any given task more than three times it would be better served by creating a new single procedure to accomplish the task that has been done manually. This reduces the chance of error in writing the same code more than three times.
This also means that changing the procedure can be done in one place.
This also means that changing the procedure can be done in one place.
void CreateANamedObject (PrimitiveType pt, string n, Vector3 p)
{We take the code that’s repeated and move it into a function. We then take the values that change between each iteration and change it into a parameter. In general, it’s best to put the parameters in the same order in which they’re used. This isn’t required, but it looks more acceptable to a programmer’s eyes.
GameObject g = GameObject.CreatePrimitive(pt);
g.name = n; g.transform.position = p;
}
void Start ()
{
CreateANamedObject(PrimitiveType.Cube, "MrCube", new Vector3(0,1,0));
}We then test the function at least once before writing any more code than we need to. If this works out, then we’re free to duplicate the line of code to accomplish what we started off doing.
void Start ()
{
CreateANamedObject(PrimitiveType.Cube, "MrCube", new Vector3(0,1,0)); CreateANamedObject(PrimitiveType.Cube, "MrsCube", new Vector3(0,2,0)); CreateANamedObject(PrimitiveType.Cube, "MissCube", new Vector3(0,3,0)); CreateANamedObject(PrimitiveType.Cube, "CubeJr", new Vector3(0,4,0));
}Again, though, we’re seeing a great deal of duplicated work. We’ve used arrays earlier, and this is as good a time as any to use them. By observation, the main thing that is changing here is the name. Therefore, we’ll need to add each name to an array.
string[] names = new string[] {"MrCube", "MrsCube", "MissCube", "CubeJr"};The variable declaration needs to change a little bit for an array. First of all, rather than using type identifier;, a pair of square brackets are used after the type. The statement starts with string[] rather than string. This is followed by the usual identifier we’re going to use to store the array of strings. Unlike an integer type, there’s no default value that can be added in for this array of strings. To com- plete the statement, we need to add in the data before the end of the statement. The new keyword is used to indicate that a new array is going to be used. The array is a special class that is built into C#. Therefore, it has some special abilities that we’ll get into later. Now that we’ve declared an array of names, we’ll need to use them.
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment