The next step is to write code and link the methods as a function to the table. Depending on the complexity of the code, we can leave it in one function, or use Natural Language Programming and Encapsulation to create multiple functions that explain our intention.
We will first focus on one function and explain how to structure the code.
This function will be called automatically each day by the Job Queue, and has to create a Cleaning Entry for each room that is occupied or has not been cleaned for a week:
OnRun() CreateCleaningEntryForEachRoom;
Since our function contains an iteration through a room record set, the Main function is a single description of the iteration.
In the following function, we again describe the business logic while programming the loop. Both the functions that we call have a meaningful name:
LOCAL CreateCleaningEntryForEachRoom() WITH Room DO IF FINDSET THEN BEGIN REPEAT IF OccupiedOrHasNotBeenCleanedForAWeek(Room) THEN CreateCleaningEntryForRoom(Room); UNTIL NEXT = 0; END;
By implementing Readability and Reducing Cyclomatic Complexity, we can create code that is easy to understand by adding a function called FindLastCleaningDate
and LastWeek
:
LOCAL OccupiedOrHasNotBeenCleanedForAWeek(Room : Record "Bed and Breakfast Room") : Boolean WITH Room DO BEGIN IF NOT Vacant THEN EXIT(TRUE); IF FindLastCleaningDate(Room) < LastWeek THEN EXIT(TRUE) END; EXIT(FALSE);
The following function returns the last record in the Cleaning Entry table for a Room sorted by Date:
LOCAL FindLastCleaningDate(Room : Record "Bed and Breakfast Room") : Date BEGIN WITH CleanEntry DO BEGIN SETCURRENTKEY(Date); SETRANGE("Room Code", Room.Code); IF FINDLAST THEN EXIT(Date); END; END; EXIT(0D);
The following function only exists for readability. It returns the last week's date:
LOCAL LastWeek() : Date EXIT(WORKDATE - 7);
And finally, we can insert the cleaning entry:
LOCAL CreateCleaningEntryForRoom(Room : Record "Bed and Breakfast Room") WITH CleanEntry DO BEGIN "Entry No." := 0; Date := WORKDATE; Status := Status::"To be Cleaned"; "Room Code" := Room.Code; INSERT; END;