markjprice / cs11dotnet7

Repository for the Packt Publishing book titled "C# 11 and .NET 7 - Modern Cross-Platform Development Fundamentals" by Mark J. Price
566 stars 206 forks source link

Chapter 5 - Story of Lamech #59

Open cgwid opened 1 year ago

cgwid commented 1 year ago

I looked through the open and closed issue titles several times and did a search but didn't see anything related. I also reviewed my code several times to see if I made a mistake somewhere but I don't see one so I think this is an issue.

Chapter: 5

Page Number: 238 of pdf

Section Title: Implementing functionality using methods

Step Number: 2, 4, 5

Problem to fix: In step 4 we set up Lamech to get married twice:

Screenshot 2023-04-12 at 3 54 15 PM

However, the instance method "Marry" defined in step 2 checks to see if the person is already married which breaks out of the recursion but also prevents subsequent marriages from occurring - "if (married) return":

Screenshot 2023-04-12 at 3 52 25 PM

So in step 4 when we try to marry zillah and lamech, it doesn't work. Then later in step 4 we call the "Procreate" method between the 2 but they aren't spouses so it triggers the exception:

Screenshot 2023-04-12 at 3 53 40 PM

Output from vscode terminal:

Screenshot 2023-04-12 at 3 56 44 PM

vs.

Output in book:

Screenshot 2023-04-12 at 3 59 36 PM

Suggested solution: Seems there could be various ways to "fix" this or restructure but here is what I came up with:

1) Have the spouse field be a List\<Person>

2) Remove the married check in "Marry" method. Instead, check if partner name is in Spouse list and return to break out of the recursion.

3) In "Procreate" method, check that the spouse is in the list before continuing.

4) Created a "DisplaySpouses" static method that takes in a person and checks their Spouse list to write the names to the console

markjprice commented 1 year ago

You are correct. Although I could solve this issue in a way similar to how you suggest, I need some time to think through all the implications of any changes I make. Meanwhile, I've added an errata item to highlight the issue for others and I will leave this issue open for now. https://github.com/markjprice/cs11dotnet7/blob/main/docs/errata/errata.md#page-235---more-about-methods

VascoMoreno commented 1 year ago

I was actually expecting this error but then the code seemed to run fine. Because of the order in which the instances are used in the example, Lamech becomes Zillah's spouse, although Adah remains Lamesh's spouse. Then the Procreate function also ends up working in the example because p1 is Lamesh for the first baby and Zillah for the second. I guess this is a good example of how code can seem to work before proper testing, but run into issues when different cases are used. Still, glad that somebody raised the issue, I was beginning to think I had misunderstood the code.