#687 – An Example of Containment

One common strategy is to use inheritance when modeling an is-a type of relationship (e.g. a Terrier is-a Dog) and to use containment when modeling a has-a type of relationship (e.g. a Family has-a Dog).

Here’s an example of containment, where a Dog object contains instances of the DogName and DogAbilities classes.

    internal class DogName
    {
        public DogName(string humanName, string nameInDogWorld)
        {
            HumanName = humanName;
            NameInDogWorld = nameInDogWorld;
        }

        public string HumanName { get; set; }
        public string NameInDogWorld { get; set; }
    }

    internal class DogAbilities
    {
        public DogAbilities(List<string> knownTricks, bool canBark)
        {
            KnownTricks = knownTricks;
            CanBark = canBark;
        }

        public List<string> KnownTricks { get; set; }
        public bool CanBark { get; set; }
    }

    public class Dog
    {
        public Dog(string humanName, string firstTrick, bool canBark)
        {
            Name = new DogName(humanName, GenerateSecretDogWorldName());

            List<string> abilities = new List<string>();
            abilities.Add(firstTrick);

            Abilities = new DogAbilities(abilities, canBark);
        }

        public void Bark()
        {
            if (Abilities.CanBark)
                Console.WriteLine("Woof!");
            else
                Console.WriteLine("Wag");
        }

        public void DoTrick(string trick)
        {
            if (Abilities.KnownTricks.Contains(trick))
                Console.WriteLine("Doing {0} trick", trick);
        }

        public void TeachTrick(string newTrick)
        {
            if (!Abilities.KnownTricks.Contains(newTrick))
                Abilities.KnownTricks.Add(newTrick);
        }

        private DogName Name { get; set; }
        private DogAbilities Abilities { get; set; }

        private string GenerateSecretDogWorldName()
        {
            return "His noble woofiness sir poops-a-lot";
        }
    }
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: