Design Issue: Two roles for a class. First for instances creating and the other for types

architecture, c#, design-patterns

Solution

If babies are always afraid of the same animals, you don't have to keep anything. You can have a method:

public bool IsAfraid(Animal animal)
{
    return animal is Wolf;
}

If babies are afraid of different animals in different places and times, you should make every animal have a property AnimalType (flag enum). The baby will then have a property AfraidOf, of type AnimalType. And then, checking if you are afraid of an animal is simple:

bool afraid = this.AfraidOf.HasFlag(animal.AnimalType);

Finally, you should probably have different types of linking to different classes for different types of relationships in your schema (Contains, Inherits, Afraid of).

Problem

Consider this class diagram: ``` +--------+ * +------------------+ * afraid-of +------------+ | Garden |------>| Animal |<------------------------| Baby | +--------+ +------------------+ +------------+ ^ | +----------+------+ | | +------+------+ +------+-----+ | Cat | | Wolf | +-------------+ +------------+ ``` Animal has two roles: - They will be walking around the garden (Class Instance) - The baby is afraid of some animals (Class Type) What baby should keep? One instance of each animal it's afraid of? (sounds like poor design) The type name? (I always try to avoid refactoring) How should this be solved? (I'm using C# and I mention it only at the end because I hope there is a general, language-free design pattern or idea here) Thanks

Original source