Skip to content

Instantly share code, notes, and snippets.

@jeremDev
Last active July 22, 2016 00:26
Show Gist options
  • Save jeremDev/d4ef8f1f7da459a0fd3e098559d2e68e to your computer and use it in GitHub Desktop.
Save jeremDev/d4ef8f1f7da459a0fd3e098559d2e68e to your computer and use it in GitHub Desktop.
Bedtime Routine
using System;
using static System.Console;
using static System.Threading.Thread;
using Throwable = System.Exception;
// This program is inspired by the XKCD Bonding comic: https://xkcd.com/1188/
public class Parent
{
public string Name => "Parent";
public void Say(string message, Child child)
{
WriteLine(this.Name + ": " + message);
child.Hear(message);
}
public void PutToBed(Child child)
{
WriteLine("Reads Stories");
WriteLine("Sings song");
while (!child.IsInBed)
{
try
{
this.Say("Go to bed.", child);
}
catch (Excuse excuse)
{
WriteLine($"{child.Name}: " + excuse.Message);
this.Say("OK", child);
}
catch (Tantrum tantrum)
{
WriteLine($"{child.Name}: " + tantrum.Message);
this.Say("It's bed time.", child);
}
}
}
}
public class Child
{
public string Name => "Child";
const bool Smoochable = true;
private int timesDelayed;
public bool IsInBed { get; private set; }
public void Say(string message)
{
WriteLine(this.Name + ": " + message);
}
void Delay()
{
this.timesDelayed++;
if (this.timesDelayed == 1)
{
throw new Tantrum("I don't want to go to bed!");
}
else if (this.timesDelayed == 2)
{
throw new Excuse("I want water!");
}
}
public void Rest()
{
if (this.IsInBed)
{
Sleep(TimeSpan.FromSeconds(10));
this.IsInBed = false;
}
}
public void Hear(string message)
{
if (message == "Go to bed.")
{
this.Delay();
this.Say("Okay");
this.IsInBed = true;
}
}
}
public class Excuse : Exception
{
public Excuse(string message) : base("(Pouting) " + message)
{
}
}
public class Tantrum : Throwable
{
public Tantrum(string message) : base("(Fussing) " + message)
{
}
}
class Program
{
static void Main()
{
Parent parent = new Parent();
Child child = new Child();
parent.PutToBed(child);
parent.Say("I love you!", child);
child.Say("I love you too!");
child.Rest();
}
}
@jeremDev
Copy link
Author

Thanks for the changes j2jensen! I made a few more minor changes, and I'm happy with the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment