2.6 Zoo Learning Activity [2 hours 45 minutes]

Encapsulation and Constructors
1.Getting Started [5 minutes]

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

A Copy your Zoo 2.5 ending code, renaming both the folder and the Visual Studio solution file for Zoo 2.6 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.6 Lastname" , using your last name. Keep the project target at .NET Framework 4.8.
Combined starting structure — Zoo 2.5
Starting structure — combined Zoo 2.5 classes
C Check Your Work
1 Build and run the copied solution. Confirm both zoos can be created, population buttons work and San Diego’s temperature display starts at 77.0.
Create objects with their required starting information
Acceptance Criteria
  • Creation calls pass the existing scenario values as arguments.
  • Constructors assign the starting state and connect contained objects.
2.Define the Employee constructor [5 minutes]
Problem

Currently MainWindow instantiates employees and assigns their field values, when it should be the responsibility of the class to handle assigning those values.

Solution

You will instantiate Employee by passing values into a constructor that assigns the required fields.

EmployeeConstructorFields — exact Zoo 2.6 declarations
Employee constructor and affected fields
A Modify Employee.cs based on the class and activity diagrams.
1 Change Name and Number to private fields named name and number.
2 Define Employee(string name, int number) and assign both parameters to their corresponding fields.
Employee constructor assigns required starting state.
Employee constructor assigns required starting state.
B Check Your Work
1 With name "Sam" and number 42, trace the assignments to this.name and this.number. This is a source trace until the creation paths are updated.
Employee constructor example
public Employee(string name, int number)
{
    this.name = name;
    this.number = number;
}
3.Define the Booth constructor [5 minutes]
BoothConstructorFields — exact Zoo 2.6 declarations
Booth constructor and affected fields
A Modify Booth.cs based on the class and activity diagrams.
1 Make TicketPrice private and rename it ticketPrice. Keep Attendant public for now.
2 Define Booth(Employee attendant, decimal ticketPrice). Assign this.Attendant = attendant; and this.ticketPrice = ticketPrice;.
Booth constructor assigns required starting state.
Booth constructor assigns required starting state.
MainWindow creates one attendant and passes that same reference into Booth.
MainWindow creates one attendant and passes that same reference into Booth.
B Check Your Work
1 With Sam’s Employee reference and price 15.00m, trace Attendant receiving that same reference and ticketPrice receiving 15.00m.
4.Define the Guest constructor [5 minutes]
GuestConstructorFields — exact Zoo 2.6 declarations
Guest constructor and affected fields
A Modify Guest.cs based on the class and activity diagrams.
1 Make Name and Age private fields named name and age. Remove new Wallet() from the wallet field declaration, leaving the private field.
2 Define Guest(string name, int age, decimal moneyBalance). Assign the name and age parameters to their matching fields, instantiate this.wallet, then call this.AddMoney(moneyBalance).
Guest constructor assigns required starting state.
Guest constructor assigns required starting state.
B Check Your Work
1 With "Darla", 11 and 5.25m, trace the private name/age assignments, wallet creation and AddMoney call. The wallet ends with balance 5.25m.
5.Define the VendingMachine constructor [5 minutes]
Problem

MainWindow is handling the instantiation of the animal snack machine and assigning its values, when the class should handle its required starting information.

Solution

You will instantiate VendingMachine by passing values into a constructor that assigns the required fields.

MachineConstructorFields — exact Zoo 2.6 declarations
VendingMachine constructor and affected fields
A Modify VendingMachine.cs based on the class and activity diagrams.
1 Make FoodPricePerPound private readonly as foodPricePerPound; make FoodStock private as foodStock. Update the class’s own references to those fields.
2 Define VendingMachine(decimal foodPrice). Assign this.foodPricePerPound = foodPrice; and call this.Fill() so the existing loop supplies the initial stock.
VendingMachine constructor assigns required starting state.
VendingMachine constructor assigns required starting state.
B Check Your Work
1 With foodPrice 0.75m, trace price assignment and Fill. The final foodStock is 195 and the machine’s money balance is still zero.
6.Define the BirthingRoom constructor [5 minutes]
RoomConstructorFields — exact Zoo 2.6 declarations
BirthingRoom constructor and affected fields
A Modify BirthingRoom.cs based on the class and activity diagrams.
1 Remove the initializer from temperature, leaving private double temperature;. Add private readonly double initialTemperature = 77.0;.
2 Define BirthingRoom(Employee doctor). Assign this.temperature = this.initialTemperature; and this.Doctor = doctor;. Keep the existing private readonly limits at 85.0 and 55.0 and the existing adjustment methods unchanged.
BirthingRoom constructor assigns required starting state.
BirthingRoom constructor assigns required starting state.
B Check Your Work
1 With Flora’s Employee reference, trace temperature becoming 77.0 and Doctor receiving Flora’s same reference. The limits retain their declaration values of 85.0 and 55.0.
7.Define the Restroom constructor [5 minutes]
RestroomConstructorFields — exact Zoo 2.6 declarations
Restroom constructor and affected fields
A Modify Restroom.cs based on the class and activity diagrams.
1 Make Capacity private readonly as capacity, and make Sex private as sex.
2 Define Restroom(int capacity, string sex) and assign the fields from the parameters.
Restroom constructor assigns required starting state.
Restroom constructor assigns required starting state.
B Check Your Work
1 With capacity 4 and sex "Female", trace the assignments. The readonly capacity receives its value inside construction.
8.Define the Animal constructor [5 minutes]
Problem

MainWindow is handling the instantiation of the animals and assigning their values, when the Animal class should handle assigning those values.

Solution

You will instantiate Animal by passing values into a constructor that assigns the required fields.

AnimalConstructorFields — exact Zoo 2.6 declarations
Animal constructor and affected fields
A Modify Animal.cs based on the class and activity diagrams.
1 Make Age and Sex private as age and sex; update the class’s own references. Keep the other current fields and behavior.
2 Define Animal(string type, string sex, string name, int age, double weight). Assign Type, sex, Name, age and Weight from the corresponding parameters.
Animal constructor assigns required starting state.
Animal constructor assigns required starting state.
B Check Your Work
1 With Dolly’s five starting arguments, trace Type "Dingo", sex "Female", Name "Dolly", age 4 and Weight 35.3. The baby field is still null until MakePregnant is called.
9.Define the Food constructor [5 minutes]
Problem

Food is instantiated in different places for different reasons, and its required weight should be assigned in Food itself.

Solution

You will instantiate Food by passing values into a constructor that assigns the required fields.

FoodConstructorFields — exact Zoo 2.6 declarations
Food constructor and affected fields
A Modify Food.cs based on the class and activity diagrams.
1 Define Food(double weight).
2 Assign this.Weight = weight;.
Food constructor assigns required starting state.
Food constructor assigns required starting state.
B Check Your Work
1 With weight 1.25, trace the constructor assigning Food.Weight to 1.25. This is a source trace, not a new UI action.
10.Define VendingMachine.GetFoodPricePerPound() [5 minutes]
MachinePriceReadSignature — exact Zoo 2.6 declarations
VendingMachine.GetFoodPricePerPound method signature
A Use the class signature and activity diagram.
1 Return this.foodPricePerPound using the return type shown in the class diagram.
VendingMachine.GetFoodPricePerPound returns the stored information.
VendingMachine.GetFoodPricePerPound returns the stored information.
B Check Your Work
1 Trace the return statement in the source. It reads the existing value without changing it.
11.Define VendingMachine.GetFoodStock() [5 minutes]
MachineStockReadSignature — exact Zoo 2.6 declarations
VendingMachine.GetFoodStock method signature
A Use the class signature and activity diagram.
1 Return this.foodStock using the return type shown in the class diagram.
VendingMachine.GetFoodStock returns the stored information.
VendingMachine.GetFoodStock returns the stored information.
B Check Your Work
1 Trace the return statement in the source. It reads the existing value without changing it.
12.Update Guest.FeedAnimal(...) [5 minutes]
A Use the new vending-machine read methods.
1 Replace every machine.FoodPricePerPound read with machine.GetFoodPricePerPound().
2 Replace the stock check’s machine.FoodStock read with machine.GetFoodStock(). Keep the wallet, payment, stock, refund and result-code logic.
Feeding reads machine configuration through methods.
Feeding reads machine configuration through methods.
B Check Your Work
1 Confirm both price reads and the price guard were updated; none should depend on the old public fields.
13.Define Animal.GetSex() [5 minutes]
AnimalSexReadSignature — exact Zoo 2.6 declarations
Animal.GetSex method signature
A Use the class signature and activity diagram.
1 Return this.sex using the return type shown in the class diagram.
Animal.GetSex returns the stored information.
Animal.GetSex returns the stored information.
B Check Your Work
1 Trace the return statement in the source. It reads the existing value without changing it.
14.Update Animal.MakePregnant() [10 minutes]
A Construct the unborn baby with its required information.
1 Keep the female/not-already-pregnant guard and the existing switch cases for "Dingo" and "Platypus".
2 In each supported case, create this.baby using the Animal constructor: the case’s type, "Male", string.Empty, age 0 and this.Weight multiplied by this.babyWeightPercentage.
3 Remove the old post-switch Sex and Weight assignments; those values now come from the constructor.
MakePregnant passes the baby state into its constructor.
MakePregnant passes the baby state into its constructor.
B Check Your Work
1 For Dolly’s starting weight 35.3, the baby constructor receives weight 3.53. Its initial name is string.Empty; the existing birth handler supplies the name after delivery.
15.Update VendingMachine.RemoveFood(double amount) [5 minutes]
A Use Food’s constructor at the existing food-creation point.
1 Replace the old parameterless food construction and following Weight assignment with foodPacket = new Food(amount);. Keep the amount/stock guard and stock subtraction.
RemoveFood creates Food with its weight immediately.
RemoveFood creates Food with its weight immediately.
B Check Your Work
1 Trace a valid amount and an amount exceeding stock. Food is created only on the successful path.
Open a zoo with its services connected
Acceptance Criteria
  • Zoo creates its own list, snack machine, birthing room and restrooms.
  • Existing employees, booth and visitor are passed into Zoo without duplicating them.
16.Define the Zoo constructor [15 minutes]
Problem

MainWindow is handling the instantiation of the zoo, its snack machine, birth area and restrooms, and assigning their values.

Solution

You will move the zoo-owned setup into the Zoo constructor.

ZooConstructorFields — exact Zoo 2.6 declarations
Zoo constructor and affected fields
A Modify Zoo.cs.
1 Remove new List<Animal>() from the private readonly animals field declaration. Make Capacity, LadiesRoom, MensRoom and Name private with lowercase names.
2 Define the constructor with the parameters shown in the class diagram. Initialize animals to a new list and assign name, capacity, TicketBooth and Visitor from the parameters.
3 Create AnimalSnackMachine using animalFoodPrice, BirthArea using doctor, and the two restrooms using restroomCapacity and the corresponding "Female" or "Male" string.
Zoo creates its owned objects and keeps supplied relationships.
Zoo creates its owned objects and keeps supplied relationships.
B Check Your Work
1 Trace which objects are created here and which references come from the caller. The supplied booth, doctor and visitor should not be replaced with duplicates.
17.Define Zoo.GetName() [5 minutes]
ZooNameReadSignature — exact Zoo 2.6 declarations
Zoo.GetName method signature
A Use the class signature and activity diagram.
1 Return this.name using the return type shown in the class diagram.
Zoo.GetName returns the stored information.
Zoo.GetName returns the stored information.
B Check Your Work
1 Trace the return statement in the source. It reads the existing value without changing it.
18.Update MainWindow.CreateComoZoo() [10 minutes]
A Update this existing creation method using the class, constructor and creation activity diagrams. Obtain the existing scenario values from your starting method; move those inputs into the appropriate constructor calls. Preserve population order, MakePregnant calls, AddAnimal calls, the first animal’s pen/tank reference and its array placement. Keep the final area refresh.
CreateComoZoo supplies its scenario values through constructors.
CreateComoZoo supplies the existing scenario values through constructors.
19.Update MainWindow.CreateSanDiegoZoo() [10 minutes]
A Update this existing creation method using the class, constructor and creation activity diagrams. Obtain the existing scenario values from your starting method; move those inputs into the appropriate constructor calls. Preserve population order, MakePregnant calls, AddAnimal calls, the first animal’s pen/tank reference and its array placement. Keep the final area refresh.
CreateSanDiegoZoo supplies its scenario values through constructors.
CreateSanDiegoZoo supplies the existing scenario values through constructors.
20.Update MainWindow.FeedAnimal(...) [5 minutes]
A Read the zoo name through its public method.
1 In the successful feeding message, replace zoo.Name with zoo.GetName(). Keep the search, transaction and result-code switch unchanged.
The existing successful-feeding message reads the zoo name through GetName.
The existing successful-feeding message reads the zoo name through GetName.
B Check Your Work
1 The private name field is read inside Zoo.GetName; MainWindow uses the returned string.
21.Update the existing creation and birth event handlers [10 minutes]
A Use the read methods where the fields became private.
1 In newComoZooButton_Click, replace this.comoZoo.Name with this.comoZoo.GetName(). In newSanDiegoZooButton_Click, replace this.sanDiegoZoo.Name with this.sanDiegoZoo.GetName(). Keep the creation-method calls and area-count messages.
2 In both birth handlers, replace baby.Sex with baby.GetSex(). Keep the birth guards, array placement, names, messages and temperature refresh.
Existing handler read replacements
Handler Read expression
newComoZooButton_Click this.comoZoo.GetName()
newSanDiegoZooButton_Click this.sanDiegoZoo.GetName()
birthDingoButton_Click baby.GetSex()
birthPlatypusButton_Click baby.GetSex()
B Check Your Work
1 Build the solution after all constructor and caller changes. Create both zoos: populations stay 3 and 2 and the original maps remain.
2 Create San Diego and confirm the temperature is 77.0. Test + and - once each.
3 Recreate Como, feed once and confirm the transaction succeeds. Recreate and birth once; read the birth message for occupancy 2, then click Get animal count in the Como column to confirm population 4; the newborn occupies the existing starting space.
MainWindow passes existing objects into Zoo, whose constructor creates its owned services.
MainWindow supplies existing objects; Zoo creates its owned services.
22.Debug the Employee constructor [5 minutes]
A Remove earlier breakpoints and start a fresh debugging session. Break on the first Employee creation in CreateComoZoo, then click New Como Zoo.
Watch before Employee construction
Expression Expected state
this.comoZoo null on this first creation
attendant Not assigned yet; null or unavailable
name Unavailable in MainWindow; constructor parameter
number Unavailable in MainWindow; constructor parameter
B Use F11 to enter Employee and F10 for assignments.
1 At the start of Employee’s constructor body, add name, number, this.name and this.number to Watch before stepping. name is "Sam" and number is 42. this refers to the new Employee. Its name field is initially null and number field is initially 0.
2 Step through both assignments and return to MainWindow. attendant now refers to that Employee.
3 Follow Booth’s constructor and confirm its Attendant is the same reference. Press F5 to continue and remove these breakpoints.
C Check Your Work
1 Explain the difference between the constructor parameter name and this.name.
23.Follow creation of the zoo-owned services [5 minutes]
A Set a breakpoint at the Zoo constructor’s first statement and click New Como Zoo. Use F11 to follow its contained-object construction.
Watch in the Zoo constructor
Expression Expected state at the first statement
name "Como Zoo"
animalFoodPrice 0.75m
doctor Flora’s existing Employee reference
visitor Darla’s existing Guest reference
this.animals null before the list assignment
this.AnimalSnackMachine null before machine creation
this.BirthArea null before room creation
this.ladiesRoom null before restroom creation
this.mensRoom null before restroom creation
B Follow the actual constructors.
1 Step over the list creation. Enter VendingMachine and observe foodPrice become 0.75m. Follow Fill: foodStock starts at 0 and becomes 65, 130 and 195; the next whole bag is rejected by the existing fit check.
2 Return to Zoo and enter BirthingRoom. Its initialTemperature is 77.0, temperature starts at 0 before its body assignment, and Doctor is assigned the same doctor parameter.
3 After both restroom assignments have executed in Zoo, expand this.ladiesRoom and this.mensRoom. Confirm their private capacity values are 4 and their sex values are "Female" and "Male". Press F5 to continue and remove these breakpoints.
C Check Your Work
1 The initial machine stock is now supplied during construction, rather than by MainWindow’s earlier FoodStock assignment.
24.Follow the Food constructor during feeding [5 minutes]
A Recreate Como. Break on foodPacket = new Food(amount) in VendingMachine.RemoveFood, then click Darla, feed dingo.
Watch at the Food creation statement
Expression Expected state
amount Approximately 0.7066667
foodPacket null before the assignment
weight Unavailable in this method; Food constructor parameter
this.foodStock Already reduced by amount; subtraction precedes Food creation
B Use F11 into Food and F10 through its assignment.
1 In Food, add weight and this.Weight to Watch before the constructor assignment. weight is approximately 0.7066667 and this.Weight starts at 0. After the assignment it holds the supplied weight.
2 Return through RemoveFood and the existing sale/feeding path. Press F5 to continue, then remove the breakpoint.
C Check Your Work
1 Confirm the completed feeding reports success. Food’s required weight is assigned before the caller receives its reference.
Complete the assignment
25.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.6
Ending structure — combined Zoo 2.6 classes
26.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.