2.5 Zoo Learning Activity [3 hours 30 minutes]

Encapsulation
1.Getting Started [5 minutes]

Continue from your completed Zoo 2.4. Use the diagrams and the directions below to make the next set of changes.

A Copy your Zoo 2.4 ending code, renaming both the folder and the Visual Studio solution file for Zoo 2.5 using your last name. Open the copied solution and restore its NuGet packages.
B In MainWindow.xaml, set the window attribute to Title="Programming Concepts 2: Zoo 2.5 Lastname" , using your last name. Keep the project target at .NET Framework 4.8.
Combined starting structure — Zoo 2.4
Starting structure — combined Zoo 2.4 classes
C Check Your Work
1 Build the copied solution. Create both zoos and confirm the population buttons and existing area controls work.
Let the BirthingRoom control its temperature
Acceptance Criteria
  • The room starts at 77.0.
  • Births and the existing temperature buttons still change the temperature.
2.Make the temperature field in BirthingRoom private [5 minutes]
Problem

Currently the Temperature field of the BirthingRoom can be manipulated from MainWindow when it should be the BirthingRoom itself that handles the temperature and any changes.

Solution

You will make the temperature field private and give other classes public methods for reading and changing it.

RoomChanges — exact Zoo 2.5 declarations
Private temperature and room methods
A Modify the BirthingRoom fields.
1 Rename Temperature to temperature and make it private. Initialize the field with private double temperature = 77.0;.
2 Remove InitialTemperature. The temperature field now receives its starting value directly. Keep Doctor. Replace the public limit fields with private readonly double maxTemperature = 85.0; and private readonly double minTemperature = 55.0;. Remove the unused Mother field: BirthAnimal receives the mother as a parameter.
3 Replace TemperatureIncrease with private readonly double temperatureIncrease = 0.5;.
B Check Your Work
1 Read the focused class diagram: temperature stores a changing value; temperatureIncrease stores the fixed increment. Outside callers will be repaired after the public methods are in place.
3.Update BirthingRoom.BirthAnimal(Animal mother) [5 minutes]
A Keep the existing birth conditions and delivery call.
1 Replace the direct increment with this.IncreaseTemperature(). Keep the mother-null, pregnancy and doctor checks and the returned baby reference. The public adjustment methods are added below before the build check.
BirthingRoom.BirthAnimal changes its own temperature before delivery.
BirthingRoom.BirthAnimal requests a bounded increase before delivery.
B Check Your Work
1 Trace both branches. Only the path with a pregnant mother and doctor requests an increase. Delivery still proceeds if the room is already at its maximum and the increase is rejected.
4.Define BirthingRoom.GetTemperature() [5 minutes]
RoomReadSignature — exact Zoo 2.5 declarations
BirthingRoom.GetTemperature method signature
A Use the class signature and activity diagram.
1 Return this.temperature using the return type shown in the class diagram.
BirthingRoom.GetTemperature returns the stored information.
BirthingRoom.GetTemperature returns the stored information.
B Check Your Work
1 Trace the return statement in the source. It reads the existing value without changing it.
5.Define BirthingRoom.ChangeTemperature(double temperatureChange) [5 minutes]
A Use the class signature and activity diagram.
1 Define private void ChangeTemperature(double temperatureChange). Compute double proposedTemperature = this.temperature + temperatureChange;. Follow the activity diagram to store it only when it is within the private minTemperature and maxTemperature limits, inclusive.
ChangeTemperature accepts a proposed temperature only within 55–85 inclusive.
ChangeTemperature updates the room-owned value.
B Check Your Work
1 Trace two independent trials, each starting at 77.0: a change of 0.5 gives 77.5; a change of -0.5 gives 76.5.
6.Define BirthingRoom.IncreaseTemperature() [5 minutes]
A Add a public void IncreaseTemperature() method. Use the activity diagram to pass the positive room-owned increment to the private helper.
IncreaseTemperature requests the room-owned positive increment.
IncreaseTemperature signature: public void IncreaseTemperature().
7.Define BirthingRoom.DecreaseTemperature() [5 minutes]
A Add a public void DecreaseTemperature() method. Use the activity diagram to pass the negative room-owned increment to the private helper.
DecreaseTemperature requests the room-owned negative increment.
DecreaseTemperature signature: public void DecreaseTemperature().
8.Update Zoo.GetTemperatureDisplay() [5 minutes]
A Read the temperature through the room’s public method.
1 Return this.BirthArea.GetTemperature().ToString("0.0") so Zoo reads through the room’s public method and retains one decimal place.
GetTemperatureDisplay formats the returned room value.
GetTemperatureDisplay formats the returned room value.
B Check Your Work
1 Confirm that formatting still produces one digit after the decimal point.
Give objects control over money
Acceptance Criteria
  • Wallet and vending-machine money fields become private.
  • Existing purchase, stock, payment and refund decisions remain in place.
9.Give control over the vending machine’s money balance to VendingMachine [5 minutes]
Problem

Currently the VendingMachine money balance can be manipulated outside the class through both the public MoneyBalance field and the public AddMoney method.

Solution

You will make the money field and helper method private so that other classes do not have access to them.

MachineChanges — exact Zoo 2.5 declarations
VendingMachine private money and readonly configuration
A Modify visibility and configuration in VendingMachine.
1 Rename MoneyBalance to moneyBalance, make it private and update its uses inside the class.
2 Rename BagSize to bagSize and FoodCapacity to foodCapacity. Make both private readonly and initialize them to 65.0 and 250.0.
10.Make VendingMachine.AddMoney private [5 minutes]
A Keep its existing payment operation.
1 Change AddMoney from public to private. Keep the amount parameter and add it to this.moneyBalance. Keep SellFood calling this helper after successful dispensing.
The private AddMoney helper records accepted payment.
The private AddMoney helper records accepted payment.
B Check Your Work
1 Trace SellFood into AddMoney in the source. An outside class uses SellFood; VendingMachine itself can still call its private helper.
11.Update VendingMachine.AddFoodBag() [5 minutes]
A Follow the activity diagram.
1 Make AddFoodBag private. Replace the old BagSize and FoodCapacity references with bagSize and foodCapacity; retain both return paths.
Update VendingMachine.AddFoodBag()
Update VendingMachine.AddFoodBag()
B Check Your Work
1 Source trace: stock 12 accepts one 65-pound bag, becomes 77 and returns true. Stock 212 rejects a bag, stays 212 and returns false.
12.Update VendingMachine.IsFull() [5 minutes]
A Follow the activity diagram.
1 Make IsFull private. Compare FoodStock with the private foodCapacity field.
Update VendingMachine.IsFull()
Update VendingMachine.IsFull()
B Check Your Work
1 Source trace: stock 12 makes IsFull return false; stock 250 makes it return true.
13.Update VendingMachine.Fill() [5 minutes]
A Follow the activity diagram.
1 Update the private configuration references and keep the existing stop-before-overflow check and bag counter.
Update VendingMachine.Fill()
Update VendingMachine.Fill()
B Check Your Work
1 Source trace: starting at stock 12, Fill adds three bags, reaches 207 and returns 3. A second Fill adds no bag, leaves stock 207 and returns 0.
14.Make VendingMachine.RemoveFood(double amount) private [5 minutes]
A Change only RemoveFood’s access modifier to private. Keep its null default, stock guard, subtraction, Food creation and return. SellFood remains the public transaction method and can call this helper inside VendingMachine.
15.Make the Wallet money balance private [5 minutes]
A Modify Wallet.cs.
1 Rename MoneyBalance to moneyBalance, make it private and update AddMoney and RemoveMoney to use that field. Keep the existing positive-deposit and limited-withdrawal checks.
WalletChanges — exact Zoo 2.5 declarations
Wallet controls its private balance
B Check Your Work
1 Trace a wallet balance of 2.00 and a withdrawal request of 3.00. The existing method still removes only 2.00.
16.Define Wallet.GetMoneyBalance() [5 minutes]
WalletReadSignature — exact Zoo 2.5 declarations
Wallet.GetMoneyBalance method signature
A Use the class signature and activity diagram.
1 Return this.moneyBalance using the return type shown in the class diagram.
Wallet.GetMoneyBalance returns the stored information.
Wallet.GetMoneyBalance returns the stored information.
B Check Your Work
1 Trace the return statement in the source. It reads the existing value without changing it.
17.Make the Guest wallet private [5 minutes]
Problem

Currently the guest’s wallet can be replaced from outside the Guest class.

Solution

You will make the wallet reference private and let the guest provide public operations for using it.

A Modify Guest.cs.
1 Rename Wallet to wallet and make it private. Instantiate the wallet directly in its field declaration, as shown below.
2 Change Guest’s own references from this.Wallet to this.wallet.
Private wallet reference
private Wallet wallet = new Wallet();
B Check Your Work
1 Read the declaration: every new Guest gets a wallet, so the creation methods will no longer create a Wallet separately.
18.Update Guest.AddMoney(decimal amount) [5 minutes]
A Use the guest’s private wallet.
1 Pass the amount into this.wallet.AddMoney(amount).
Guest.AddMoney delegates the deposit.
Guest.AddMoney delegates the deposit.
MainWindow deposits through Guest into its privately owned Wallet.
MainWindow deposits through Guest into its privately owned Wallet.
B Check Your Work
1 Trace the amount from Guest.AddMoney into Wallet.AddMoney. The wallet still rejects a nonpositive deposit.
19.Define Guest.GetMoneyBalance() [5 minutes]
GuestReadSignature — exact Zoo 2.5 declarations
Guest.GetMoneyBalance method signature
A Use the class signature and activity diagram.
1 Return this.wallet.GetMoneyBalance() using the return type shown in the class diagram.
Guest.GetMoneyBalance returns the stored information.
Guest.GetMoneyBalance returns the stored information.
B Check Your Work
1 Trace the return statement in the source. It reads the existing value without changing it.
20.Make Guest.RemoveMoney private [5 minutes]
A Keep the existing withdrawal operation.
1 Change RemoveMoney to private and use this.wallet.RemoveMoney(amount). Keep its decimal return value.
Guest.RemoveMoney returns the amount supplied by Wallet.
Guest.RemoveMoney returns the amount supplied by Wallet.
B Check Your Work
1 Confirm Guest.FeedAnimal can still call this private method from inside Guest.
21.Update Guest.FeedAnimal(...) [5 minutes]
A Read the wallet through its public method.
1 Keep the wallet-null check using this.wallet. Replace the direct balance read with this.wallet.GetMoneyBalance().
2 Keep all existing result codes, payment checks, refund operations and food/animal calls.
Guest.FeedAnimal retains its transaction flow with the private wallet.
Guest.FeedAnimal retains its transaction flow with the private wallet.
B Check Your Work
1 Compare the updated conditions with your previous method. Only the wallet access changes; the meaning of each result code stays the same.
Give Animal control over its internal state
Acceptance Criteria
  • The unborn baby reference is private.
  • Percentage fields are readonly and the animal uses them internally.
22.Give the Animal control over its fields [5 minutes]
AnimalChanges — exact Zoo 2.5 declarations
Animal private baby and fixed percentages
A Modify the fields and their references inside Animal.cs.
1 Rename Baby to baby and make it private. Update all uses of that field inside Animal; keep a local variable named baby in Reproduce.
2 Make the five existing percentage fields private readonly with the lowercase names shown in the table. Add private readonly double moveWeightLossPercentage = 0.03;. Use those field names in Eat, MakePregnant, GetPortionSize and Reproduce.
Animal percentages
Field Value
afterbirthPercentage 0.1
babyWeightPercentage 0.1
eatBabyWeightGainPercentage 0.1
eatWeightGainPercentage 0.8
portionSizePercentage 0.02
moveWeightLossPercentage 0.03
B Check Your Work
1 GetIsPregnant still reports whether this.baby is non-null. Outside classes use that method instead of accessing baby directly.
23.Update Animal.Move() [5 minutes]
A Use the new movement percentage.
1 Calculate double weightLossAmount = this.Weight * this.moveWeightLossPercentage;, then subtract it with this.Weight -= weightLossAmount;.
Move now uses the configured three-percent loss.
Move now uses the configured three-percent loss.
B Check Your Work
1 Trace Dolly’s starting weight of 35.3. A single Move now produces approximately 34.241; the configured rate is three percent.
Let Zoo control additions to its population
Acceptance Criteria
  • The population list is private.
  • Callers register animals through AddAnimal and read the population size through GetAnimalCount.
24.Make the list of animals private [5 minutes]
Problem

The Zoo class should be the only class with direct access to the list of animals. Additionally, it is possible to add null to the list, which is not something we want to happen.

Solution

You will make the list private, refactor the code to use it and make sure an animal is not null before adding it.

A Modify Zoo.cs.
1 Rename Animals to animals and make it private readonly. Keep new List<Animal>() in the field declaration.
2 Update all list references inside Zoo, including wake, weight and search methods, to use this.animals.
B Check Your Work
1 Trace the weight and search methods using this.animals. Their loops and return behavior remain the same.
25.Define Zoo.AddAnimal(Animal animal) [5 minutes]
AddAnimalSignature — exact Zoo 2.5 declarations
Zoo.AddAnimal signature
A Use a null check before changing the list.
1 Add the supplied animal to this.animals only if animal != null.
AddAnimal ignores a null reference.
AddAnimal ignores a null reference.
B Check Your Work
1 Trace a real animal and null through the diagram. Only the real animal reaches Add. This method does not check for duplicate references.
26.Define Zoo.GetAnimalCount() [5 minutes]
PopulationReadSignature — exact Zoo 2.5 declarations
Zoo.GetAnimalCount method signature
A Use the class signature and activity diagram.
1 Return this.animals.Count using the return type shown in the class diagram.
Zoo.GetAnimalCount returns the stored information.
Zoo.GetAnimalCount returns the stored information.
B Check Your Work
1 Trace the return statement in the source. It reads the existing value without changing it.
27.Update Zoo.BirthAnimal(Animal mother) [5 minutes]
A Use the zoo-owned registration method.
1 Keep the delivered-baby check. Inside it, call this.AddAnimal(baby) instead of adding to the list directly.
BirthAnimal routes successful births through AddAnimal.
BirthAnimal routes successful births through AddAnimal.
B Check Your Work
1 The returned baby is still the same reference passed back to the existing birth handler for array placement.
28.Make the MainWindow fields private [5 minutes]
A Change the fields and their references in MainWindow.xaml.cs.
1 Rename ComoZoo to comoZoo and SanDiegoZoo to sanDiegoZoo and make both private.
2 Rename ZooAnimalCount to zooAnimalCount and ZooAverageAnimalWeight to zooAverageAnimalWeight and make both private.
3 Update uses of those fields throughout MainWindow. Keep method names, XAML names, strings and Click handler names unchanged.
29.Restrict the remaining internal helpers [5 minutes]
A Change each method in the table from public to private. Keep its signature, body and existing internal calls otherwise unchanged. Each helper has no current outside caller. Keep public operations such as MoveAnimal, PlaceAnimal, GetAnimalLocation and CalculateAverageAnimalWeight accessible.
Internal helpers
Class Methods to make private
MainWindow CreateComoZoo(), CreateSanDiegoZoo(), DisplayMessage(string message), DisplayAnimalArea(Zoo zoo, string zooName), FeedAnimal(Zoo zoo, string zooName, string animalName, string guestName), MoveFeaturedAnimal(Zoo zoo, string zooName, string direction)
Pen ClearLocation(), FindAnimalPosition(Animal animal), IsValidPosition(int position), MoveAnimalInPen(int positionChange)
Tank ContainsAnimal(Animal animal), FindAnimalColumn(Animal animal), FindAnimalRow(Animal animal), IsValidLocation(int row, int column), MoveAnimalInTank(int rowChange, int columnChange)
Zoo CalculateTotalAnimalWeight()
30.Update MainWindow.CreateComoZoo() [10 minutes]
A Use the creation activity diagram and the changed class interfaces to update this existing method. Preserve its scenario data, pregnancy calls, pen/tank placement and display refreshes. Remove setup for members now initialized or removed in their owning classes, including the unused BirthArea.Mother assignment.
CreateComoZoo keeps the existing objects and uses public operations for protected state.
CreateComoZoo uses the objects’ controlled public operations.
31.Update MainWindow.CreateSanDiegoZoo() [10 minutes]
A Use the creation activity diagram and the changed class interfaces to update this existing method. Preserve its scenario data, pregnancy calls, pen/tank placement and display refreshes. Remove setup for members now initialized or removed in their owning classes, including the unused BirthArea.Mother assignment.
CreateSanDiegoZoo keeps the existing objects and uses public operations for protected state.
CreateSanDiegoZoo uses the objects’ controlled public operations.
32.Remove the redundant MainWindow temperature helper [5 minutes]
A Delete ChangeSanDiegoTemperature(double temperatureChange). The existing + and - handlers will call the room’s focused public actions directly. Their complete replacement bodies appear in the next task.
33.Update the existing count and temperature handlers [10 minutes]
A Keep the existing handler guards and messages; change these expressions.
1 In the Como population-count handler, replace this.comoZoo.Animals.Count with this.comoZoo.GetAnimalCount(). In the San Diego handler, replace this.sanDiegoZoo.Animals.Count with this.sanDiegoZoo.GetAnimalCount(). The table below gives the complete replacement assignments.
2 Replace both temperature handlers with the complete code below. Keep their existing XAML event hookups unchanged. The room chooses the fixed step; MainWindow reads the result for display.

Keep the existing Click="decreaseSanDiegoTemperatureButton_Click" and Click="increaseSanDiegoTemperatureButton_Click" attribute values on their corresponding buttons.

Complete existing temperature handlers
private void decreaseSanDiegoTemperatureButton_Click(object sender, RoutedEventArgs e)
{
    if (this.sanDiegoZoo == null)
    {
        this.DisplayMessage("Create San Diego Zoo first.");
        return;
    }

    this.sanDiegoZoo.BirthArea.DecreaseTemperature();

    this.temperatureTextBlock.Text = this.sanDiegoZoo.BirthArea.GetTemperature().ToString("0.0");
}

private void increaseSanDiegoTemperatureButton_Click(object sender, RoutedEventArgs e)
{
    if (this.sanDiegoZoo == null)
    {
        this.DisplayMessage("Create San Diego Zoo first.");
        return;
    }

    this.sanDiegoZoo.BirthArea.IncreaseTemperature();

    this.temperatureTextBlock.Text = this.sanDiegoZoo.BirthArea.GetTemperature().ToString("0.0");
}
3 In newSanDiegoZooButton_Click, read and format the initial display with this.sanDiegoZoo.BirthArea.GetTemperature().ToString("0.0").
Updated count assignments
Handler Replacement statement
getComoZooAnimalCount_Click this.zooAnimalCount = this.comoZoo.GetAnimalCount();
getSanDiegoZooAnimalCount_Click this.zooAnimalCount = this.sanDiegoZoo.GetAnimalCount();
B Check Your Work
1 Build the solution after all caller updates. Create both zoos and confirm population counts 3 and 2, the original maps and successful feeding.
2 Set a breakpoint at the closing brace of VendingMachine.Fill. Recreate Como and fill once; while paused inside VendingMachine inspect this.FoodStock as 207. Press F5 to continue. Recreate San Diego and fill once; inspect this.FoodStock as 212, then continue and remove the breakpoint. A further whole bag would exceed capacity.
3 Create San Diego and confirm its temperature display starts at 77.0. Use + then - to see 77.5 then 77.0.
4 Reset San Diego to 77.0. Click + sixteen times to reach 85.0; another + leaves it at 85.0. From 85.0, click - sixty times to reach 55.0; another - leaves it at 55.0. Reset before the later birth checks. A birth at the maximum still proceeds while its temperature stays at 85.0.
34.Check the access rules [5 minutes]
A Make these temporary compile checks, one at a time, then remove each test line.
1 After creating an animal in CreateComoZoo, temporarily add this.comoZoo.animals.Add(animal);. Build and observe the private-access error, then remove that test line.
2 Temporarily add this.comoZoo.AnimalSnackMachine.AddMoney(3000.00m);. Build and observe the private-method access error, then remove that test line.
B Check Your Work
1 Build again after deleting the test statements. Private members can still be expanded in the debugger; that does not make them public to C# callers.
35.Follow the wallet through the feeding sequence [5 minutes]
A Remove earlier breakpoints, start a fresh debugging session and create Como.
1 Set a breakpoint on the funds check in Guest.FeedAnimal and click Darla, feed dingo. Add the expressions in the table before stepping.
Watch inside Guest.FeedAnimal
Expression Expected state
this.wallet Existing Wallet reference
this.wallet.moneyBalance 5.25 before payment
foodCost 0.53
this.moneyBalance Unavailable; that field belongs to Wallet
amount Unavailable here; it is a parameter of later wallet methods
B Use F11 and F10 to follow the actual calls.
1 Step into Wallet.GetMoneyBalance. this now refers to Wallet, where this.moneyBalance is 5.25. Return to the funds check.
2 Follow Guest.RemoveMoney into Wallet.RemoveMoney. amount is 0.53; after subtraction the private balance is 4.72.
3 Continue through dispensing. When VendingMachine.AddMoney runs, this refers to the machine and amount is 0.53. After addition its private moneyBalance is 0.53. Press F5 to continue.
C Check Your Work
1 Confirm the purchase succeeds. Remove the payment breakpoints before the next check.
36.Follow the public animal-registration method [5 minutes]
A Set a breakpoint at the first AddAnimal(animal) call in CreateComoZoo and click New Como Zoo.
Watch at the registration call
Expression In MainWindow before the call
animal.Name "Dolly"
this.comoZoo.animals Empty list; the debugger can inspect private members
this.animals Unavailable until inside Zoo.AddAnimal
1 Before the call, animal refers to Dolly. The zoo exists, but its private animals list still has Count 0.
2 Use F11 into Zoo.AddAnimal. The parameter animal becomes available in Zoo; observe this.animals.Count become 1 after Add executes.
3 Continue creation, then click Get animal count in the Como column and confirm the displayed population count is 3. The creation message itself reports pen occupancy, not population. Remove the breakpoint.
B Check Your Work
1 As a source trace, pass null through AddAnimal’s condition. No list mutation occurs. Use the existing application calls for the runtime walkthrough.
37.Check the completed encapsulation changes [5 minutes]
A Check Your Work
1 Recreate Como and set a breakpoint on the first statement in Zoo.WakeAllAnimals. Click Wake all animals once. While paused, add this.animals[0].Weight, this.animals[1].Weight and this.animals[2].Weight to Watch. Step over the loop iterations until all Move calls finish, then inspect the weights as approximately 34.241, 32.786 and 15.035. Press F5 to continue and remove the breakpoint.
2 Recreate Como and birth once. Read the birth message for pen occupancy 2, then click Get animal count in the Como column to confirm population count 4. The existing occupied-space guard still blocks a second birth into the same space.
3 Build with the temporary access tests removed. Keep the public-field suppression on classes that still have public fields; remove it from Wallet and MainWindow, whose fields are now private.
Complete the assignment
38.Review the ending structure [5 minutes]
A Use the ending diagrams to explain how the objects now control or expose their state.
Combined ending structure — Zoo 2.5
Ending structure — combined Zoo 2.5 classes
39.Submit a zipped Visual Studio solution [5 minutes]
A Save and build your .NET Framework 4.8 solution. Zip the solution and submit it to the Feedback System. Submit the Feedback System URL to the correct assignment in Canvas.