ooploose-couplingcohesion

How to refactor these classes to interact each other?


My requirement is to use the name of the shape and draw that shape with the dimensions like in the method Draw('rectangle', 'l:10,w:20');.

  1. There should be validation of the dimensions against the type of the shape.
  2. These classes can be refactored to add more classes or change the hierarchy.
  3. No run-time checking like reflection should be used. The problem needs to be solved with class design only.
  4. Don't use if-else or switch statements in the client method Draw.

Requirement:

public static void main()
{
    // Provide the shape and it's dimensions
    Draw('rectangle', 'l:10,w:20');
    Draw('circle', 'r:15');
}

I created the following classes. I considered low(loose) coupling and high cohesion by making two class hierarchies so they can grow on it's own. I kept the responsibilities of drawing to one class and generating the dimension to the other class.

My question is about creating these objects and interacting each other to achieve my requirements.

public abstract class Shape()
{
    Dimension dimension;
    public void abstract SetDimentions(Dimension dimension);
    public void abstract Draw()
}

public void Rectangle()
{
    void override SetDimensions(RectangleDimension dimension)
    {
    }

    void override Draw()
    {
        // Use the 'dimention' to draw
    }
}

public void Circle()
{
    void override SetDimensions(CircleDimension dimension)
    {
    }

    void override Draw()
    {
        // Use the 'dimention' to draw
    }
}

public class RectangleDimension
{
    public int length {get; set; }
    public int width { get; set; }
}

public class CircleDimension
{
    public int circle { get; set; }
}

Solution

  • You will need to use reflection in whatever OOP technology you are using. You receive a String like "circle" and you need to call a method with that name.

    This is how you can do that in Java and this is how you can do it in C#.