Rather than dealing with everything in one lump, the modular method breaks it down into smaller pieces. Each piece deals with a particular task and can broken down yet further until the pieces are more manageable.
Programming this way makes solving problem much easier as you only have do deal with one thing at once.
This will continue now when it comes to accessing the information in the array, a number of small functions are used, which when combined deal with the whole lot.
The next function is one which will find the next available space in the array, that a new object can be stored in. We will call this function FirstFreeWorkObject().
Initially you might think you could just add one to the variable numWorkObjects and store the new object there, but we also want to allow for objects being removed - remember the isFree field?
function FirstFreeWorkObject()
for thisObject = 1 to TopWorkObject()
if workObject[ thisObject ].isFree > 0 then exit
next thisObject
if thisObject > MAX_WORKOBJECTS then thisObject = 0
endfunction thisObject
This function counts from 1 to the top object, checking each entry in the array to see if the .isFree field contains a 1 - indicating the entry is free for use. If so, it uses the exit command, which leaves the loop - the program jumps to after the next instruction.
If none of the the entries are free, it finishes the for/next loop normally, but this in itself still provides a valid result.
It relies on the way the next instruction works - normally you wouldn't think about this because you generally only use the index value within the loop.
When the program gets to the next instruction at the end of the loop, it increments the index value (thisObject in this case) and then compares it to the limit set in the for statement (which was TopWorkObject()). If the result is higher, it exist the loop, otherwise it goes back to just after the for.
The important thing here is the fact that it increments the counter and then checks, so when the count is complete, the index value is actually higher than the limit set. Which in this case it would be the entry in the array immediately after the top entry. Since it is above the top entry, it is by definition free for use.
All we have to do then is to make sure this is not higher than the maximum allowed as defined by MAX_WORKOBJECTS, so we have the if statement to do just that.
If thisObject is higher than MAX_WORKOBJECTS, it is set to zero. An object value zero is not valid and will be trapped by the WorkObjectValid() function.
This is the modular principal at work, the FirstFreeWorkObject() function performs just one task - it finds the first free object or it returns a zero if there isn't one.
The WorkObjectValid() function will later indicate that the zero returned by this function is no good as an object and what ever part of the program called these, will take the necessary action as a result.
No comments:
Post a Comment