0

I'm refactoring a class (Controller) which handles a tree. Because there are many different types (around 20) in the tree. It uses often following structure to handle for example an insertion:

  1. Determine type of the object
  2. Do some type specific things and insert object into tree

    public void AddChildren(Animal animal)
    {
        var cat = animal as Cat;
        if (cat != null)
        {
            AddCat(cat);
            return;
        }
    
        var dog = animal as Dog;
        if (dog != null)
        {
            AddDog(dog);
            return;
        }
    }
    
    public void AddCat(Cat cat)
    {
        //do some cat specific things
        //add to tree
    }
    

So the logic for determining the type of an object is used in many places within the class. Is there a good approach to concentrate this logic in one place?

1 Answer 1

1

You might want to use the Strategy(GoF) pattern:

http://en.wikipedia.org/wiki/Strategy_pattern

  1. Create an interface LivingAnimal with a method addToTree(Tree tree)
  2. Implement this interface in objects Cat, Dog, etc.
  3. in Cat.addToTree(Tree tree) (and other objects), do your cat specific stuff, and add itself in the tree (tree.add(this))
  4. In your controller, create a method addChildren(LivingAnimal p). This method finds the correct type of object (Cat, Dog, etc.) and calls addToTree(tree) on it.

When you're using Strategy(GoF), you're delegating the responsibility to the right object. In this case, you'll simplify your controller and keep a high cohesion on the various objects.

3
  • Thanks, nice suggestion. But unfortunately I cannot change the objects which are placed in the tree. They come from a library which I cannot change.
    – faceman
    Mar 20, 2014 at 16:20
  • What about creating a Proxy(GoF) for each objects, and applying Strategy on the proxy? Here's the Proxy pattern: en.wikipedia.org/wiki/Proxy_pattern . If you decide to use Proxy(GoF) on a library, you are also protecting yourself against a modification of the library. Mar 21, 2014 at 1:35
  • 1
    Thanks for your suggestions. If I get enough time from my boss ;). I will try it with the proxy and state pattern.
    – faceman
    Mar 21, 2014 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.